Spaces:
Runtime error

File size: 2,315 Bytes
ad79323
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
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;
}