From be0f537dc4fe384eef09436833c6407e6482c16d Mon Sep 17 00:00:00 2001
From: Rafi Zadanly <zadanlyr@gmail.com>
Date: Thu, 9 Nov 2023 15:40:16 +0700
Subject: Initial commit

---
 src/app/api/auth/login/route.tsx | 36 ++++++++++++++++++++++++++++++++++++
 1 file changed, 36 insertions(+)
 create mode 100644 src/app/api/auth/login/route.tsx

(limited to 'src/app/api/auth/login/route.tsx')

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
-- 
cgit v1.2.3

