aboutsummaryrefslogtreecommitdiff
path: root/api/src/modules/auth/auth.service.ts
blob: c874b05d9ebd5f01dfd9499162a92de3d039653c (plain)
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
import bcrypt from 'bcryptjs';
import { eq } from 'drizzle-orm';
import { db } from '../../db/client';
import { users } from '../../db/schema/users';
import type { LoginData, RegisterData } from './auth.schema';

export async function registerUser(data: RegisterData) {
  const existingUser = await db.select().from(users).where(eq(users.email, data.email)).limit(1);
  if (existingUser.length > 0) {
    throw new Error('Email já está em uso.');
  }

  const salt = await bcrypt.genSalt(10);
  const passwordHash = await bcrypt.hash(data.password, salt);

  const [newUser] = await db.insert(users).values({
    name: data.name,
    email: data.email,
    password_hash: passwordHash,
    gross_salary: data.gross_salary || 0,
  }).returning();

  const { password_hash, ...userWithoutPassword } = newUser;
  return userWithoutPassword;
}

export async function loginUser(data: LoginData) {
  const [user] = await db.select().from(users).where(eq(users.email, data.email)).limit(1);
  
  if (!user) {
    throw new Error('Email ou senha inválidos.');
  }

  const isValid = await bcrypt.compare(data.password, user.password_hash);
  if (!isValid) {
    throw new Error('Email ou senha inválidos.');
  }

  const { password_hash, ...userWithoutPassword } = user;
  return userWithoutPassword;
}