refactor(auth): centralize role checks into utility
Removed direct user role string checks and replaced with type-safe utils.
This commit is contained in:
@@ -0,0 +1,43 @@
|
||||
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)
|
||||
}
|
||||
Reference in New Issue
Block a user