2025-05-17 15:07:22 +02:00

47 lines
1.4 KiB
TypeScript

import { NextRequest, NextResponse } from "next/server";
import bcrypt from 'bcryptjs';
import jwt from 'jsonwebtoken';
import prisma from "@/app/prisma";
interface Body {
username: string;
password: string;
}
export async function POST(request: NextRequest) {
try {
const body: Body = await request.json();
if (!body.username || !body.password) {
return NextResponse.json({ error: "Missing required fields" }, { status: 400 });
}
const user = await prisma.user.findUnique({
where: {
username: body.username,
},
});
if (!user) {
return NextResponse.json({ error: "User not found" }, { status: 404 });
}
const validPassword = await bcrypt.compare(body.password, user.password);
if (!validPassword) {
return NextResponse.json({ error: "Invalid password" }, { status: 401 });
}
if(!process.env.JWT_SECRET) {
return NextResponse.json({ error: "No JWT secret found" }, { status: 500 });
}
const token = jwt.sign({ id: user.id }, process.env.JWT_SECRET, { expiresIn: "7d" });
return NextResponse.json({ message: "Login successful", token }, { status: 200 });
} catch (error: any) {
return NextResponse.json({ error: "Internal Server Error" }, { status: 500 });
}
}