2025-02-26 17:43:30 +08:00

25 lines
965 B
TypeScript

import { NextApiRequest, NextApiResponse } from "next";
import { PrismaClient } from "@prisma/client";
import bcrypt from "bcrypt";
import jwt from "jsonwebtoken";
const prisma = new PrismaClient()
const SECRET_KEY = process.env.JWT_SECRET as string;
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method !== "POST") return res.status(405).json({ message: "Method not allowed" });
const { email, password } = req.body;
const user = await prisma.user.findUnique({ where: { email } });
if (!user) return res.status(401).json({ message: "Invalid credentials" });
const isMatch = await bcrypt.compare(password, user.password);
if (!isMatch) return res.status(401).json({ message: "Invalid credentials" });
const token = jwt.sign({ email: user.email }, SECRET_KEY, { expiresIn: "1d" });
res.setHeader("Set-Cookie", `token=${token}; HttpOnly; Path=/; Secure`);
res.json({ token });
}