Re_Figma_Code/USER_ROLE_MANAGEMENT.md

340 lines
8.7 KiB
Markdown

# User Role Management Feature
## 🎯 Overview
Added a comprehensive User Role Management system for administrators to assign roles to users directly from the Settings page.
---
## ✅ What Was Built
### Frontend Components
#### 1. **UserRoleManager Component**
Location: `src/components/admin/UserRoleManager/UserRoleManager.tsx`
**Features:**
- **Search Users from Okta** - Real-time search with debouncing
- **Role Assignment** - Assign USER, MANAGEMENT, or ADMIN roles
- **Statistics Dashboard** - Shows count of users in each role
- **Elevated Users List** - Displays all ADMIN and MANAGEMENT users
- **Auto-create Users** - If user doesn't exist in database, fetches from Okta and creates them
- **Self-demotion Prevention** - Admin cannot demote themselves
**UI Components:**
- Statistics cards showing admin/management/user counts
- Search input with dropdown results
- Selected user card display
- Role selector dropdown
- Assign button with loading state
- Success/error message display
- Elevated users list with role badges
---
### Backend APIs
#### 2. **New Route: Assign Role by Email**
`POST /api/v1/admin/users/assign-role`
**Purpose:** Assign role to user by email (creates user from Okta if doesn't exist)
**Request:**
```json
{
"email": "user@royalenfield.com",
"role": "MANAGEMENT" // or "USER" or "ADMIN"
}
```
**Response:**
```json
{
"success": true,
"message": "Successfully assigned MANAGEMENT role to John Doe",
"data": {
"userId": "abc-123",
"email": "user@royalenfield.com",
"displayName": "John Doe",
"role": "MANAGEMENT"
}
}
```
**Flow:**
1. Check if user exists in database by email
2. If not exists → Search Okta API
3. If found in Okta → Create user in database with assigned role
4. If exists → Update user's role
5. Prevent self-demotion (admin demoting themselves)
---
#### 3. **Existing Routes (Already Created)**
**Get Users by Role**
```
GET /api/v1/admin/users/by-role?role=ADMIN
GET /api/v1/admin/users/by-role?role=MANAGEMENT
```
**Get Role Statistics**
```
GET /api/v1/admin/users/role-statistics
```
Response:
```json
{
"success": true,
"data": {
"statistics": [
{ "role": "ADMIN", "count": 3 },
{ "role": "MANAGEMENT", "count": 12 },
{ "role": "USER", "count": 145 }
],
"total": 160
}
}
```
**Update User Role by ID**
```
PUT /api/v1/admin/users/:userId/role
Body: { "role": "MANAGEMENT" }
```
---
### Settings Page Updates
#### 4. **New Tab: "User Roles"**
Location: `src/pages/Settings/Settings.tsx`
**Changes:**
- Added 4th tab to admin settings
- Tab layout now responsive: 2 columns on mobile, 4 on desktop
- Tab order: User Settings → **User Roles** → Configuration → Holidays
- Only visible to ADMIN role users
**Tab Structure:**
```
┌─────────────┬────────────┬──────────────┬──────────┐
│ User │ User Roles │ Config │ Holidays │
│ Settings │ (NEW! ✨) │ │ │
└─────────────┴────────────┴──────────────┴──────────┘
```
---
### API Service Updates
#### 5. **User API Service**
Location: `src/services/userApi.ts`
**New Functions:**
```typescript
userApi.assignRole(email, role) // Assign role by email
userApi.updateUserRole(userId, role) // Update role by userId
userApi.getUsersByRole(role) // Get users filtered by role
userApi.getRoleStatistics() // Get role counts
```
---
## 🎨 UI/UX Features
### Statistics Cards
```
┌──────────────────┐ ┌──────────────────┐ ┌──────────────────┐
│ Administrators │ │ Management │ │ Regular Users │
│ 3 │ │ 12 │ │ 145 │
│ 👑 ADMIN │ │ 👥 MANAGEMENT │ │ 👤 USER │
└──────────────────┘ └──────────────────┘ └──────────────────┘
```
### Role Assignment Section
1. **Search Input** - Type name or email
2. **Results Dropdown** - Shows matching Okta users
3. **Selected User Card** - Displays chosen user details
4. **Role Selector** - Dropdown with 3 role options
5. **Assign Button** - Confirms role assignment
### Elevated Users List
- Shows all ADMIN and MANAGEMENT users
- Regular USER role users are not shown (too many)
- Each user card shows:
- Role icon and badge
- Display name
- Email
- Department and designation
---
## 🔐 Access Control
### ADMIN Only
- View User Roles tab
- Search and assign roles
- View all elevated users
- Create users from Okta
- Demote users (except themselves)
### MANAGEMENT & USER
- Cannot access User Roles tab
- See info message about admin features
---
## 🔄 User Creation Flow
### Scenario 1: User Exists in Database
```
1. Admin searches "john@royalenfield.com"
2. Finds user in search results
3. Selects user
4. Assigns MANAGEMENT role
5. ✅ User role updated
```
### Scenario 2: User Doesn't Exist in Database
```
1. Admin searches "new.user@royalenfield.com"
2. Finds user in Okta search results
3. Selects user
4. Assigns MANAGEMENT role
5. Backend fetches full details from Okta
6. Creates user in database with MANAGEMENT role
7. ✅ User created and role assigned
```
### Scenario 3: User Not in Okta
```
1. Admin searches "fake@email.com"
2. No results found
3. If admin types email manually and tries to assign
4. ❌ Error: "User not found in Okta. Please ensure the email is correct."
```
---
## 🎯 Role Badge Colors
| Role | Badge Color | Icon | Access Level |
|------|-------------|------|--------------|
| ADMIN | 🟡 Yellow | 👑 Crown | Full system access |
| MANAGEMENT | 🔵 Blue | 👥 Users | Read all data, enhanced dashboards |
| USER | ⚪ Gray | 👤 User | Own requests and assigned workflows |
---
## 📊 Test Scenarios
### Test 1: Assign MANAGEMENT Role to Existing User
```
1. Login as ADMIN
2. Go to Settings → User Roles tab
3. Search for existing user
4. Select MANAGEMENT role
5. Click Assign Role
6. Verify success message
7. Check user appears in Elevated Users list
```
### Test 2: Create New User from Okta
```
1. Search for user not in database (but in Okta)
2. Select ADMIN role
3. Click Assign Role
4. Verify user is created AND role assigned
5. Check statistics update (+1 ADMIN)
```
### Test 3: Self-Demotion Prevention
```
1. Login as ADMIN
2. Search for your own email
3. Try to assign USER or MANAGEMENT role
4. Verify error: "You cannot demote yourself from ADMIN role"
```
### Test 4: Role Statistics
```
1. Check statistics cards show correct counts
2. Assign roles to users
3. Verify statistics update in real-time
```
---
## 🔧 Backend Implementation Details
### Controller: `admin.controller.ts`
**New Function: `assignRoleByEmail`**
```typescript
1. Validate email and role
2. Check if user exists in database
3. If NOT exists:
a. Import UserService
b. Search Okta by email
c. If not found in Okta return 404
d. If found Create user with assigned role
4. If EXISTS:
a. Check for self-demotion
b. Update user's role
5. Return success response
```
---
## 📁 Files Modified
### Frontend (3 new, 2 modified)
```
✨ src/components/admin/UserRoleManager/UserRoleManager.tsx (NEW)
✨ src/components/admin/UserRoleManager/index.ts (NEW)
✨ Re_Figma_Code/USER_ROLE_MANAGEMENT.md (NEW - this file)
✏️ src/services/userApi.ts (MODIFIED - added 4 functions)
✏️ src/pages/Settings/Settings.tsx (MODIFIED - added User Roles tab)
```
### Backend (2 modified)
```
✏️ src/controllers/admin.controller.ts (MODIFIED - added assignRoleByEmail)
✏️ src/routes/admin.routes.ts (MODIFIED - added POST /users/assign-role)
```
---
## 🎉 Complete Feature Set
✅ Search users from Okta
✅ Create users from Okta if they don't exist
✅ Assign any of 3 roles (USER, MANAGEMENT, ADMIN)
✅ View role statistics
✅ View all elevated users (ADMIN + MANAGEMENT)
✅ Regular users hidden (don't clutter the list)
✅ Self-demotion prevention
✅ Real-time search with debouncing
✅ Beautiful UI with gradient cards
✅ Role badges with icons
✅ Success/error messaging
✅ Loading states
✅ Test IDs for testing
✅ Mobile responsive
✅ Admin-only access
---
## 🚀 Ready to Use!
The feature is fully functional and ready for testing. Admins can now easily manage user roles directly from the Settings page without needing SQL or manual database access!
**To test:**
1. Log in as ADMIN user
2. Navigate to Settings
3. Click "User Roles" tab
4. Start assigning roles! 🎯