File size: 1,696 Bytes
9a92a42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { IUser } from '../model/user.model';

// Role hierarchy for permission checks
const ROLE_HIERARCHY: { [key: string]: number } = {
    trainee: 0,
    trainer: 1,
    organization: 2,
    admin: 3,
};

/**
 * Check if user has minimum required role level
 */
export const hasMinimumRole = (userRole: string, minimumRole: string): boolean => {
    return (ROLE_HIERARCHY[userRole] || 0) >= (ROLE_HIERARCHY[minimumRole] || 0);
};

/**
 * Check if user can manage events (trainer level or above)
 */
export const canManageEvents = (userRole: string): boolean => {
    return hasMinimumRole(userRole, 'trainer');
};

/**
 * Check if user can manage event day for a specific event
 * User must be:
 * 1. At trainer level or above, AND
 * 2. Either the event creator OR from the same organization
 */
export const canManageEventDay = async (
    user: IUser,
    event: any
): Promise<boolean> => {
    // Must be at least trainer level
    if (!canManageEvents(user.role)) {
        return false;
    }

    // Event creator can always manage
    if (event.createdBy.toString() === user._id.toString()) {
        return true;
    }

    // Admin can manage any event
    if (user.role === 'admin') {
        return true;
    }

    // For trainers and organizations, check if they belong to the same organization
    if (user.role === 'trainer') {
        // Trainer must belong to the event's organization
        return user.organization?.toString() === event.organization.toString();
    }

    if (user.role === 'organization') {
        // Organization user must be the event's organization
        return user._id.toString() === event.organization.toString();
    }

    return false;
};