Files
AM_CMS_Summative/app/api/auth/register/route.ts
T
2026-11-06 10:02:29 +00:00

60 lines
1.9 KiB
TypeScript

import { NextRequest, NextResponse } from "next/server";
import { prisma } from "../../../lib/prisma";
import { hashPassword } from "../../../lib/auth";
export async function POST(request: NextRequest) { // handles post request to /api/auth/register endpoint
try {
const body = await request.json(); // converts json req to obj, request.json reads only the req body
const { email, password, name } = body; // breaks down the body obj into variables
if (!email || !password) { // checks required variables
return NextResponse.json(
{ error: "Email and password are required" },
{ status: 400 }
)
};
const existingUser = await prisma.users.findUnique({ // checks whether that email is already registered
where: { email }
});
if (existingUser) {
return NextResponse.json(
{ error: "User with this email already exists" },
{ status: 409 }
)
}
const hashedPassword = await hashPassword(password);
const user = await prisma.users.create({ // creates new user with hashed password
data: {
email,
passwordHash: hashedPassword,
name
}
});
const response = NextResponse.json( // crafts the response with a message and user obj thats just been added
{
message: "User reigseted successfully",
user: {
id: user.id,
email: user.email,
name: user.name
}
},
{ status: 201}
);
return response; // returns the crafted response
} catch (error) {
console.error("Registration error:", error);
return NextResponse.json(
{ error: "Internal server error" },
{ status: 500 }
);
}
}