File size: 1,648 Bytes
1c8e50c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/**
 * Utility functions for role-based access control
 */

/**
 * Check if a user has admin privileges
 * @param {Object} user - User object with role property
 * @returns {boolean} True if user is an admin
 */
export const isAdmin = (user) => {
  if (!user || !user.role) return false;
  const role = user.role.toUpperCase();
  return role === 'ROLE_ADMIN' || role === 'ADMIN';
};

/**
 * Check if a user has a specific role
 * @param {Object} user - User object with role property
 * @param {string} roleName - Role name to check (with or without ROLE_ prefix)
 * @returns {boolean} True if user has the role
 */
export const hasRole = (user, roleName) => {
  if (!user || !user.role || !roleName) return false;
  
  const userRole = user.role.toUpperCase();
  const checkRole = roleName.toUpperCase();
  
  // Handle both formats: "ADMIN" and "ROLE_ADMIN"
  const roleWithPrefix = checkRole.startsWith('ROLE_') ? checkRole : `ROLE_${checkRole}`;
  const roleWithoutPrefix = checkRole.replace('ROLE_', '');
  
  return userRole === roleWithPrefix || userRole === roleWithoutPrefix;
};

/**
 * Get display name for a role
 * @param {string} role - Role string (e.g., "ROLE_ADMIN", "ROLE_CUSTOMER")
 * @returns {string} Human-readable role name
 */
export const getRoleDisplayName = (role) => {
  if (!role) return 'User';
  
  const roleMap = {
    'ROLE_ADMIN': 'Administrator',
    'ADMIN': 'Administrator',
    'ROLE_CUSTOMER': 'Team Member',
    'CUSTOMER': 'Team Member',
    'ROLE_USER': 'User',
    'USER': 'User',
  };
  
  return roleMap[role.toUpperCase()] || 'User';
};

export default {
  isAdmin,
  hasRole,
  getRoleDisplayName,
};