import bcrypt from 'bcrypt'; import { SignJWT } from 'jose'; import { NextResponse } from 'next/server'; import { PrismaClient } from '@prisma/client'; import { env } from '@utils/env'; import { findUserByEmail, readUserCsv, User } from '../functions/csvReadWrite'; const usingPrisma = false; let prisma: PrismaClient; if (usingPrisma) prisma = new PrismaClient(); export async function POST(req: Request) { try { const json = await req.json(); // Parse incoming JSON data const { email, password } = json.body; const userData = await readUserCsv(); console.log(userData); console.log("Email:", email); // ! remove console.log("Password:", password); // ! remove let user; if (usingPrisma) { user = await prisma.user.findUnique({ where: { email, // use the email to uniquely identify the user }, }); } else { user = findUserByEmail(userData, email); } if (user && bcrypt.compareSync(password, usingPrisma ? user.hashedPassword : user.password)) { // todo remove password from returned user // get user and relations if (usingPrisma) user = await prisma.user.findUnique({ where: { id: user.id }, include: { scientist: { include: { earthquakes: true, observatories: true, artifacts: true, superior: true, subordinates: true, }, }, purchasedArtifacts: true, }, }); const secret = new TextEncoder().encode(env.JWT_SECRET_KEY); const token = await new SignJWT({ userId: user.id }) .setProtectedHeader({ alg: "HS256" }) .setExpirationTime("2w") .sign(secret); const response = NextResponse.json({ message: "Login successful!", user, token }, { status: 200 }); response.cookies.set("jwt", token, { httpOnly: true, secure: process.env.NODE_ENV === "production", sameSite: "strict", maxAge: 3600 * 168 * 2, // 2 weeks path: "/", }); return response; } else { return NextResponse.json({ message: "Email and/or password are invalid" }, { status: 401 }); } } catch (error) { console.error("Error in signup endpoint:", error); return NextResponse.json({ message: "Internal Server Error" }, { status: 500 }); } finally { if (usingPrisma) await prisma.$disconnect(); } }