File size: 1,390 Bytes
2ab1980
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a37afe6
2ab1980
a37afe6
2ab1980
 
 
 
4e2a593
 
 
 
 
 
 
2ab1980
 
 
 
 
 
 
 
 
 
 
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
import bcrypt from 'bcrypt';
import { prisma } from './prisma';

const SALT_ROUNDS = 10;

export class AuthService {
    /**
     * Hashes a password using bcrypt.
     */
    static async hashPassword(password: string): Promise<string> {
        return bcrypt.hash(password, SALT_ROUNDS);
    }

    /**
     * Compares a plaintext password with a hashed password.
     */
    static async verifyPassword(password: string, hash: string): Promise<boolean> {
        return bcrypt.compare(password, hash);
    }

    /**
     * Finds a user by email and includes organization context.
     */
    static async findUserByEmail(email: string, organizationId: string) {
        return prisma.user.findUnique({
            where: { email_organizationId: { email, organizationId } },
            include: { organization: true }
        });
    }

    static async findUserByEmailOnly(email: string) {
        return prisma.user.findFirst({
            where: { email },
            include: { organization: true }
        });
    }

    /**
     * Checks if a user is allowed to access an organization.
     */
    static isUserAllowedInOrg(user: any, targetOrgId: string): boolean {
        // Super admin can access anything
        if (user.role === 'SUPER_ADMIN') return true;
        
        // Org Admin/Member must match the ID
        return user.organizationId === targetOrgId;
    }
}