Prashikshak / API /src /util /role.util.ts
Abhisingh-18's picture
Initial commit: Prashikshak - disaster management training platform
9a92a42
Raw
History Blame Contribute Delete
1.7 kB
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;
};