diff options
| author | Rafi Zadanly <zadanlyr@gmail.com> | 2023-11-09 15:40:16 +0700 |
|---|---|---|
| committer | Rafi Zadanly <zadanlyr@gmail.com> | 2023-11-09 15:40:16 +0700 |
| commit | be0f537dc4fe384eef09436833c6407e6482c16d (patch) | |
| tree | 194b1ad3f34396cb8149075bbbd38b854aedf361 /src/app/api/auth/login | |
| parent | 5d5401ae36e7e0c8eb38ccd943c1aa44a9573d35 (diff) | |
Initial commit
Diffstat (limited to 'src/app/api/auth/login')
| -rw-r--r-- | src/app/api/auth/login/route.tsx | 36 |
1 files changed, 36 insertions, 0 deletions
diff --git a/src/app/api/auth/login/route.tsx b/src/app/api/auth/login/route.tsx new file mode 100644 index 0000000..d4da662 --- /dev/null +++ b/src/app/api/auth/login/route.tsx @@ -0,0 +1,36 @@ +import { NextRequest, NextResponse } from "next/server"; +import { prisma } from "prisma/client"; +import { cookies } from "next/headers" +import { Credential } from "@/common/types/auth" +import bcrypt from "bcrypt"; +import jwt from "jsonwebtoken"; + +const JWT_SECRET = process.env.JWT_SECRET as string + +export async function POST(request: NextRequest) { + const body = await request.json() + + const user = await prisma.user.findUnique({ + where: { username: body.username }, + include: { + company: true + } + }) + + if (!user) { + return NextResponse.json({ error: 'User not found' }, { status: 404 }) + } + + if (!await bcrypt.compare(body.password, user.password)) { + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) + } + + const credential: Credential = { + ...user, + token: jwt.sign(user, JWT_SECRET, { expiresIn: '10y' }) + } + + cookies().set('credential', JSON.stringify(credential)) + + return NextResponse.json(credential) +}
\ No newline at end of file |
