User & Role Management Module¶
Overview¶
The User & Role Management module handles internal system users, staff accounts, role-based access control (RBAC), and permission management. It provides fine-grained access control for administrators, loan officers, support staff, and other internal users.
API Prefixes: /api/v1/user/* (users, roles, and policies share this router namespace)
Route Verification Status¶
- Source Routers:
app/api/v1/endpoints/users.py,app/api/v1/endpoints/roles.py,app/api/v1/endpoints/policy.py - Live Route Count: 36 (users: 16, roles: 11, policy: 9)
- Verification State: Verified (2026-06-28)
- Canonical Tracking:
docs/API_ROUTE_DOCUMENTATION_TODO.md - Verification Method: Route decorators extracted from
@r.<method>(...)in the source routers above.
Key Features¶
User Management¶
1. User Types¶
- Admin: Full system access and configuration
- Manager: Department/region management
- Loan Officer: Loan application review and approval
- Support Staff: Customer service and support
- Compliance Officer: AML and regulatory compliance
- Reports Analyst: Report generation and analysis
- Data Entry: Data entry and verification staff
2. User Lifecycle¶
- User creation and provisioning
- Profile and contact management
- Status tracking (Active, Inactive, Suspended, Terminated)
- Permission assignment
- Password and credential management
- Location/department assignment
3. User Activity Tracking¶
- Login history and timestamps
- Real-time activity monitoring
- Location history tracking
- Session management
- Audit trail of all actions
Role-Based Access Control (RBAC)¶
1. Role Hierarchy¶
- Define role hierarchy with parent/child relationships
- Department-level role scoping
- Regional role restrictions
- Role inheritance and overrides
2. Permission System¶
- Fine-grained permissions for all operations
- Resource-level permissions
- Action-based permissions (create, read, update, delete)
- Conditional permissions (e.g., approve only up to limit)
3. Role Assignment¶
- Assign roles to users
- Multi-role support per user
- Role assignment with effective dates
- Role expiration management
API Endpoints (Verified Against Live Router)¶
For complete endpoint inventories (method, effective path, source line), use:
- docs/API_ROUTE_LIVE_REFERENCE.md -> section users.py (16 routes)
- docs/API_ROUTE_LIVE_REFERENCE.md -> section roles.py (11 routes)
- docs/API_ROUTE_LIVE_REFERENCE.md -> section policy.py (9 routes)
Important routing note:
- Role and policy endpoints are effectively exposed under /api/v1/user/* because roles.py and policy.py attach to the shared user_router object.
Database Models¶
User Models¶
- User: Main user record
- ID, username, email, phone
- First/last name
- Status (Active, Inactive, Suspended)
- Department/region assignment
-
Created/updated timestamps
-
UserProfile: Extended user information
- Title and job description
- Department
- Manager/supervisor
- Contact details
-
Office location
-
UserSettings: User preferences
- Theme, language
- Notification settings
-
Default dashboard view
-
UserRole: User to role mapping
- User ID to role ID
- Assignment date and expiry
- Effective dates
Role Models¶
- Role: Role definition
- Role name and code
- Description
- Parent role (hierarchy)
-
Status (Active, Inactive)
-
Permission: Fine-grained permission
- Permission identifier
- Resource and action
- Description
-
Conditions (optional)
-
RoleAction: Role to action mapping
- Role ID to permission ID
-
Assignment details
-
ActionPermission: Action/permission linking
- Action to permission mapping
- Condition rules
Activity & Audit Models¶
- SessionHistory: User login/logout tracking
- LocationHistory: User location tracking
- AuditLog: All user actions and changes
- AccessLog: Resource access logging
User Roles & Hierarchy¶
Role: System Administrator¶
Permissions:
- Create/edit/delete users
- Manage roles and permissions
- System configuration
- View all reports
- Manage system settings
- User approval workflows
- Emergency password reset
Role: Loan Manager¶
Permissions:
- Create loan products
- Approve loans up to 500,000 ZMW
- Assign loans to loan officers
- View loan portfolio
- Generate loan reports
- Override loan decisions (up to limit)
Restrictions:
- Can only manage own branch/region
Role: Loan Officer¶
Permissions:
- Review loan applications
- Request additional documents
- Run loan scoring
- Forward for approval
- Cannot directly approve (delegated to Loan Manager)
Restrictions:
- Can only view assigned applications
Role: Support Agent¶
Permissions:
- View customer information
- View transaction history
- Process customer requests
- Create support tickets
- Cannot modify customer data
RBAC Implementation¶
Permission Structure¶
Resource: loan
Actions:
- create_product
- edit_product
- approve_application
- approve_loan
- disburse_loan
- mark_default
- write_off
Permission Combination: loan.approve_loan
Role-Permission Assignment¶
Role: Loan Officer
├─ loan.review_application ✓
├─ loan.request_documents ✓
├─ loan.run_scoring ✓
├─ loan.approve_application ✗
└─ loan.disburse_loan ✗
Role: Loan Manager
├─ loan.review_application ✓
├─ loan.approve_application ✓
├─ loan.approve_loan ✓ (up to 500K)
├─ loan.disburse_loan ✓
└─ loan.write_off ✓
User Provisioning Flow¶
New Staff Onboarding¶
1. User Creation
├─ Admin creates user account
├─ Assign email and phone
├─ Set department/branch
└─ Generate temporary password
2. Role Assignment
├─ Select appropriate role(s)
├─ Set role effective date
├─ Assign permissions
└─ Review access level
3. System Access Setup
├─ Enable system logins
├─ Configure default workspace
├─ Grant initial permissions
└─ Send access credentials via secure channel
4. Training & Activation
├─ Provide system training
├─ Test access to assigned features
├─ Reset temporary password
├─ Activate user account
└─ Monitor first activities
5. Offboarding (Termination)
├─ Disable user account
├─ Revoke all permissions
├─ Audit trail of access
├─ Archive user data
└─ Redistribute responsibilities
Controllers & Business Logic¶
User Controllers¶
controller/users.py: User managementcreate_user(): Create new userupdate_user(): Update user profileassign_roles(): Assign role to userget_user_permissions(): Calculate effective permissions-
track_user_activity(): Log user actions -
controller/user_provisioning.py: Provisioning workflows provision_user(): Complete onboardingdeprovision_user(): Offboardingbulk_provision(): Create multiple users
Role Controllers¶
controller/roles.py: Role managementcreate_role(): Create new roleassign_permission(): Add permission to role-
get_role_permissions(): Get all permissions for role -
controller/permissions.py: Permission management create_permission(): Create new permissioncheck_permission(): Validate user permissionenforce_permission(): Enforce at runtime
Configuration¶
User Configuration¶
{
"username": "john.doe",
"email": "john.doe@bank.com",
"phone": "+260712345678",
"first_name": "John",
"last_name": "Doe",
"title": "Senior Loan Officer",
"department": "Loans",
"branch": "Lusaka Main",
"manager": "jane.smith",
"status": "active"
}
Role Configuration¶
{
"code": "loan_officer",
"name": "Loan Officer",
"description": "Handles loan applications and underwriting",
"parent_role": null,
"permissions": [
"loan.review_application",
"loan.request_documents",
"loan.run_scoring",
"customer.view_details",
"customer.update_profile",
"report.loan_portfolio"
],
"status": "active"
}
Permission Configuration¶
{
"code": "loan.approve_loan",
"resource": "loan",
"action": "approve",
"description": "Approve loan for disbursement",
"conditions": {
"amount_limit": 500000,
"department": "loans"
}
}
Permission Check Examples¶
Simple Permission Check¶
@permission_required("loan.approve_loan")
def approve_loan(loan_id: str):
# Only loan managers can execute this
return approve_loan_logic(loan_id)
Conditional Permission Check¶
def approve_loan_with_limit(loan_id: str, amount: float):
user = get_current_user()
# Check if user has permission
if not user.has_permission("loan.approve_loan"):
raise PermissionError()
# Check amount limit
max_approval_amount = 500000
if amount > max_approval_amount:
raise LimitExceededError()
return approve_loan_logic(loan_id)
Department-Scoped Permission¶
def view_branch_loans(user: User, branch_id: str):
# Check permission
if not user.has_permission("loan.view_portfolio"):
raise PermissionError()
# Check if user belongs to branch
if user.branch_id != branch_id:
raise ScopingError("Not authorized for this branch")
return get_loans_by_branch(branch_id)
Activity Monitoring¶
User Activity Tracking¶
Events Tracked:
- Login/logout with timestamp and IP
- API calls with resource and action
- Data access (customer, loan, transaction)
- Configuration changes
- Permission changes
- Approval actions
- Data exports
Stored in: AuditLog table
Real-Time Monitoring¶
Dashboard Shows:
- Currently logged in users
- Active sessions by department
- Unusual access patterns
- Failed login attempts
- Permission denials
- Bulk operations
Error Handling¶
User Management Errors¶
USER_NOT_FOUND: User ID doesn't existDUPLICATE_USERNAME: Username already existsINVALID_EMAIL: Invalid email formatPERMISSION_DENIED: User lacks permissionUSER_INACTIVE: User account is inactiveROLE_NOT_FOUND: Role doesn't existCIRCULAR_ROLE_HIERARCHY: Circular parent/child relationship
Testing¶
Test Categories¶
- User creation and role assignment
- Permission checking at runtime
- RBAC enforcement
- Activity logging
- Department/branch scoping
- Permission inheritance
Test Files¶
tests/test_users.py: User managementtests/test_roles.py: Role managementtests/test_policy.py: Policy enforcement
Performance Considerations¶
- Permission Caching: Cache role permissions in Redis
- User Lookup: Index on username for fast lookup
- Bulk Operations: Batch user creation
- Activity Logging: Async log writing
- Session Caching: Cache user sessions
Security Features¶
- Password Security: Bcrypt hashing, complexity rules
- Session Management: Session timeout, multi-session limits
- Audit Logging: All actions logged with user/timestamp
- Permission Checks: Enforce at every resource access
- Department Scoping: Restrict data by department
- Activity Monitoring: Alert on suspicious patterns
- Access Revocation: Immediate revocation on role removal
Integration Points¶
Internal Modules¶
- Authentication: Verify user credentials
- Transaction Processing: Approval workflows
- Loan Management: Loan officer approval
- Customer Management: Department-based scoping
- Policy Management: User policy enforcement
- Audit Logging: All user actions