summaryrefslogtreecommitdiff
path: root/src/app/api/auth/login/route.tsx
blob: d4da66263f9def377b67d0203036ef5f5165838c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
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)
}