# Initial User Role Permission Setup for Organization Users

## ✅ Completed Actions

### 1. Updated Default Role Assignment
All user creation endpoints now default to `role_id: 5` instead of `role_id: 3`:
- ✅ `authController.js` - User registration
- ✅ `userController.js` - User creation
- ✅ `contactController.js` - Contact creation
- ✅ `contactTreeController.js` - Role filtering
- ✅ `superAdminController.js` - Role filtering
- ✅ `Contact.js` model - Default role assignment

### 2. Assigned User Role to Existing Organization Users
Successfully updated **140 users across 2 organizations**:
- ✅ Bangladesh Navy: 137 users
- ✅ Bangladesh Police: 3 users

All users now have `role_id: 5` with 39 basic permissions.

## 📊 Current Database Role Structure

| ID | Name | Level | Actual Permissions |
|----|------|-------|-------------------|
| 1  | Super Admin | 100 | Full system access |
| 2  | Admin | 50 | Elevated privileges |
| 3  | User | 30 | Manager-level permissions (⚠️ Name/description mismatch) |
| 4  | Officer | 20 | Operational access |
| 5  | Manager | 10 | Basic user permissions (⚠️ **This is the USER role despite the name**) |

## ⚠️ Important Note: Role Naming Issue

**There's a naming inconsistency in the database:**
- Role ID 5 is named "Manager" but has **User-level permissions (level 10)**
- Role ID 3 is named "User" but has **Manager-level permissions (level 30)**

**This doesn't affect functionality** - all users are correctly assigned role_id 5 which has the 39 basic user permissions. However, the names are misleading.

## 🔧 Recommended: Fix Role Naming

To fix the role naming issue, you should run the clean and rebuild script:

```bash
cd backend
node clean_and_rebuild_roles_permissions.js
```

This will create the proper role structure:
- ID 1: Super Admin (level 100)
- ID 2: Admin (level 50)
- ID 3: Manager (level 30)
- ID 4: Officer (level 20)
- ID 5: User (level 10) ✅ Correct name and permissions

**⚠️ Warning**: After running this script, you may need to reassign users to the correct roles if their role_id changes.

## 📋 User Role Permissions (role_id: 5)

The User role includes these 39 permissions:

### Basic Access
- `user.read` - View user information
- `unit.read`, `department.read`, `designation.read`, `rank.read` - View organizational structure
- `contact.read` - View contacts

### Messaging & Communication
- `message.create`, `message.read`, `message.update`, `message.delete` - Full message access
- `conversation.create`, `conversation.read`, `conversation.update` - Conversation access
- `notification.read`, `notification.update` - Notification management
- `individual_messaging.access`, `individual_messaging.send` - Individual messaging

### Profile & Settings
- `profile.read`, `profile.update`, `profile.change_password` - Profile management
- `profile_page.access`, `profile_page.edit`, `profile_page.change_avatar` - Profile page access
- `settings.access`, `settings.profile`, `settings.security`, `settings.notifications`, `settings.privacy`, `settings.preferences` - Settings access

### Directory & Navigation
- `directory.access`, `directory.search` - Directory access
- `dashboard.view` - Dashboard access
- `conversations.access` - Conversations page access

### Files & Feedback
- `file.upload`, `file.download` - File operations
- `feedback.create`, `feedback.read` - Feedback submission
- `feedback_form.access`, `feedback_form.submit` - Feedback form access

## 🚀 Usage

### Creating New Users

All new users in any organization will automatically get the User role (ID: 5):

```javascript
// Example: Creating a new user in Bangladesh Navy
const newUser = await User.create({
  name: 'New Officer',
  organization_id: 1,
  rank_id: 5,
  service_no: 'SVC12345',
  unit_id: 1,
  department_id: 1,
  designation_id: 1,
  email: 'officer@navy.mil.bd',
  password_hash: hashedPassword,
  // role_id automatically defaults to 5 (User)
});
```

### Creating Users for Specific Organization

```javascript
// Example: Creating a user in Bangladesh Police
const policeUser = await User.create({
  name: 'Police Officer',
  organization_id: 2,
  email: 'officer@police.gov.bd',
  // ... other fields
  // role_id defaults to 5 (User)
});
```

### Assigning Different Roles

To assign a different role (e.g., Admin):

```javascript
const adminUser = await User.create({
  name: 'Admin User',
  organization_id: 1,
  role_id: 2, // Explicitly set to Admin
  // ... other fields
});
```

## 🔄 Re-running the Script

To assign User role to new organization users or specific organization:

```bash
# Assign to all organizations
node assign_user_role_to_organization_users.js

# Assign to specific organization (e.g., organization_id = 2)
node assign_user_role_to_organization_users.js --org 2
```

## 📊 Statistics

After setup:
- **Total Organizations**: 2
- **Total Users**: 143
- **Users with User Role**: 140
- **Super Admins**: 1
- **Admins**: 2

## ✅ Benefits

### 1. Consistent Permissions
All organization users have the same basic permissions regardless of which organization they belong to.

### 2. Data Isolation
Even though roles are global, users can only access data from their own organization through `organization_id` filtering.

### 3. Easy User Management
New users are automatically assigned appropriate permissions without manual intervention.

### 4. Scalable
Adding new organizations is simple - users automatically get the correct role and permissions.

## 🔍 Verification

To verify users in an organization have correct roles:

```sql
-- Check users in Bangladesh Navy (org_id: 1)
SELECT u.id, u.name, u.email, r.name as role_name, r.level
FROM users u
JOIN roles r ON u.role_id = r.id
WHERE u.organization_id = 1 AND u.is_active = 1;

-- Check role distribution across all organizations
SELECT 
  o.name as organization,
  r.name as role,
  COUNT(*) as user_count
FROM users u
JOIN organizations o ON u.organization_id = o.id
JOIN roles r ON u.role_id = r.id
WHERE u.is_active = 1
GROUP BY o.name, r.name
ORDER BY o.name, r.level DESC;
```

## 📝 Next Steps

1. ✅ **Done**: Updated default role assignment in all controllers
2. ✅ **Done**: Assigned User role to all organization users
3. ⚠️ **Recommended**: Run `clean_and_rebuild_roles_permissions.js` to fix role naming
4. 🔄 **Optional**: Update existing users if needed after role structure fix
5. ✅ **Done**: Test user creation in different organizations
6. 📱 **Todo**: Update frontend to reflect new role structure

## 🆘 Support

If you encounter issues:
1. Check the database role structure with `node check_roles_structure.js`
2. Verify user permissions are correctly assigned
3. Ensure organization_id is properly set for all users
4. Check that role_permissions table has correct mappings

## 📄 Related Files

- `assign_user_role_to_organization_users.js` - Script to assign User role
- `check_roles_structure.js` - Check current role structure
- `clean_and_rebuild_roles_permissions.js` - Rebuild roles and permissions
- `UPDATE_DEFAULT_USER_ROLE_SUMMARY.md` - Technical summary of changes

