From 1519b2d0f16119432ed79d1be1781c23e9364223 Mon Sep 17 00:00:00 2001 From: sam Date: Wed, 26 Feb 2025 17:43:30 +0800 Subject: [PATCH] =?UTF-8?q?=F0=9F=9A=A7=20register=20endpoint=20to=20retur?= =?UTF-8?q?n=20token?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pages/api/login.ts | 4 ++-- pages/api/register.ts | 10 ++++++++-- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/pages/api/login.ts b/pages/api/login.ts index dda9377..2a5c6a6 100644 --- a/pages/api/login.ts +++ b/pages/api/login.ts @@ -3,7 +3,7 @@ import { PrismaClient } from "@prisma/client"; import bcrypt from "bcrypt"; import jwt from "jsonwebtoken"; -const prisma = new PrismaClient(); +const prisma = new PrismaClient() const SECRET_KEY = process.env.JWT_SECRET as string; export default async function handler(req: NextApiRequest, res: NextApiResponse) { @@ -17,7 +17,7 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse) const isMatch = await bcrypt.compare(password, user.password); if (!isMatch) return res.status(401).json({ message: "Invalid credentials" }); - const token = jwt.sign({ userId: user.id, email: user.email }, SECRET_KEY, { expiresIn: "1h" }); + const token = jwt.sign({ email: user.email }, SECRET_KEY, { expiresIn: "1d" }); res.setHeader("Set-Cookie", `token=${token}; HttpOnly; Path=/; Secure`); res.json({ token }); diff --git a/pages/api/register.ts b/pages/api/register.ts index 5e1e976..3f66d80 100644 --- a/pages/api/register.ts +++ b/pages/api/register.ts @@ -1,8 +1,11 @@ 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; -const prisma = new PrismaClient(); export default async function handler(req: NextApiRequest, res: NextApiResponse) { if (req.method !== "POST") return res.status(405).json({ message: "Method not allowed" }); @@ -17,5 +20,8 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse) data: { email, password: hashedPassword }, }); - res.status(201).json({ message: "User registered", user }); + const token = jwt.sign({ email: user.email }, SECRET_KEY, { expiresIn: "1d" }); + + res.setHeader("Set-Cookie", `token=${token}; HttpOnly; Path=/; Secure`); + res.status(201).json({ message: "User registered", user, token }); }