Spaces:
Runtime error
Runtime error
| import { Prisma } from "@prisma/client"; | |
| import { normalizeEmail } from "@/lib/utils"; | |
| import { createSession, setSessionCookie } from "@/server/auth/session"; | |
| import { db } from "@/server/db"; | |
| import { AppError, isPrismaUniqueConstraintError } from "@/server/errors"; | |
| import type { LoginInput, RegisterInput } from "@/server/validation/auth"; | |
| import { hashPassword, verifyPassword } from "@/server/auth/password"; | |
| function sanitizeUser(user: { | |
| id: string; | |
| firstName: string; | |
| lastName: string; | |
| email: string; | |
| }) { | |
| return { | |
| id: user.id, | |
| firstName: user.firstName, | |
| lastName: user.lastName, | |
| email: user.email, | |
| }; | |
| } | |
| export async function registerUser(input: RegisterInput) { | |
| const data = { | |
| firstName: input.firstName.trim(), | |
| lastName: input.lastName.trim(), | |
| email: normalizeEmail(input.email), | |
| passwordHash: await hashPassword(input.password), | |
| }; | |
| try { | |
| const user = await db.user.create({ | |
| data, | |
| select: { | |
| id: true, | |
| firstName: true, | |
| lastName: true, | |
| email: true, | |
| }, | |
| }); | |
| const session = await createSession(user.id); | |
| await setSessionCookie(session.token, session.expiresAt); | |
| return sanitizeUser(user); | |
| } catch (error) { | |
| if (isPrismaUniqueConstraintError(error, "email")) { | |
| throw new AppError("البريد الإلكتروني ده مستخدم قبل كده.", 409); | |
| } | |
| throw error; | |
| } | |
| } | |
| export async function loginUser(input: LoginInput) { | |
| const email = normalizeEmail(input.email); | |
| const user = await db.user.findUnique({ | |
| where: { email }, | |
| }); | |
| if (!user) { | |
| throw new AppError("البريد الإلكتروني أو كلمة السر مش صح.", 401); | |
| } | |
| const passwordMatches = await verifyPassword(input.password, user.passwordHash); | |
| if (!passwordMatches) { | |
| throw new AppError("البريد الإلكتروني أو كلمة السر مش صح.", 401); | |
| } | |
| const session = await createSession(user.id); | |
| await setSessionCookie(session.token, session.expiresAt); | |
| return sanitizeUser(user); | |
| } | |
| export function sanitizePrismaError(error: unknown) { | |
| if (error instanceof Prisma.PrismaClientKnownRequestError) { | |
| throw new AppError("حصل خطأ في قاعدة البيانات، حاول تاني.", 500); | |
| } | |
| throw error; | |
| } | |