82 lines
2.2 KiB
TypeScript
Raw Normal View History

import bcrypt from 'bcrypt';
import { SignJWT } from 'jose';
import { NextResponse } from 'next/server';
2025-04-29 18:07:25 +01:00
import { PrismaClient } from '@prisma/client';
import { env } from '@utils/env';
2025-04-29 18:07:25 +01:00
import { findUserByEmail, readUserCsv, User } from '../functions/csvReadWrite';
2025-04-29 18:07:25 +01:00
const usingPrisma = false;
let prisma: PrismaClient;
if (usingPrisma) prisma = new PrismaClient();
2025-05-09 10:30:12 +01:00
export async function POST(req: Request) {
2025-04-29 18:07:25 +01:00
try {
2025-05-09 10:30:12 +01:00
const json = await req.json(); // Parse incoming JSON data
const { email, password } = json.body;
2025-04-29 18:07:25 +01:00
const userData = await readUserCsv();
console.log(userData);
console.log("Email:", email); // ! remove
console.log("Password:", password); // ! remove
2025-05-09 10:30:12 +01:00
let user;
2025-04-29 18:07:25 +01:00
if (usingPrisma) {
2025-05-09 10:30:12 +01:00
user = await prisma.user.findUnique({
2025-04-29 18:07:25 +01:00
where: {
2025-05-09 10:30:12 +01:00
email, // use the email to uniquely identify the user
2025-04-29 18:07:25 +01:00
},
});
} else {
2025-05-09 10:30:12 +01:00
user = findUserByEmail(userData, email);
2025-04-29 18:07:25 +01:00
}
2025-05-09 10:30:12 +01:00
if (user && bcrypt.compareSync(password, usingPrisma ? user.hashedPassword : user.password)) {
2025-04-29 18:07:25 +01:00
// todo remove password from returned user
2025-05-09 10:30:12 +01:00
// get user and relations
if (usingPrisma)
user = await prisma.user.findUnique({
where: { id: user.id },
include: {
scientist: {
include: {
earthquakes: true,
observatories: true,
artifacts: true,
2025-05-09 10:30:12 +01:00
superior: true,
subordinates: true,
},
},
purchasedArtifacts: true,
2025-05-09 10:30:12 +01:00
},
});
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;
2025-04-29 18:07:25 +01:00
} 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();
}
}