44 lines
1.2 KiB
TypeScript
44 lines
1.2 KiB
TypeScript
export const ROLES = {
|
|
CITIZEN: 'CITIZEN',
|
|
OPERATOR: 'OPERATOR',
|
|
ADMIN: 'ADMIN'
|
|
} as const
|
|
|
|
export type Role = keyof typeof ROLES
|
|
|
|
export const ROLE_LEVELS: Record<string, number> = {
|
|
[ROLES.CITIZEN]: 1,
|
|
[ROLES.OPERATOR]: 2,
|
|
[ROLES.ADMIN]: 3
|
|
}
|
|
|
|
export function normalizeRole(role?: string | null): string {
|
|
return role?.trim().toUpperCase() ?? ''
|
|
}
|
|
|
|
export function isRole(userRole: string | undefined | null, targetRole: string): boolean {
|
|
return normalizeRole(userRole) === targetRole.toUpperCase()
|
|
}
|
|
|
|
export function hasMinimumRole(userRole: string | undefined | null, requiredRole: string): boolean {
|
|
const userLvl = ROLE_LEVELS[normalizeRole(userRole)] || 0
|
|
const reqLvl = ROLE_LEVELS[requiredRole.toUpperCase()] || 0
|
|
return userLvl >= reqLvl
|
|
}
|
|
|
|
export function isAdmin(userRole?: string | null): boolean {
|
|
return isRole(userRole, ROLES.ADMIN)
|
|
}
|
|
|
|
export function isOperator(userRole?: string | null): boolean {
|
|
return isRole(userRole, ROLES.OPERATOR)
|
|
}
|
|
|
|
export function isCitizen(userRole?: string | null): boolean {
|
|
return isRole(userRole, ROLES.CITIZEN)
|
|
}
|
|
|
|
export function canAccess(userRole: string | undefined | null, requiredRole: string): boolean {
|
|
return hasMinimumRole(userRole, requiredRole)
|
|
}
|