11 KiB
Staff User Account Management Implementation
Overview
This document describes the implementation of optional user account creation and management for Staff members in the PX360 system.
Features Implemented
1. Optional One-to-One User Relation
- Status: ✅ Already exists in Staff model
- The Staff model already has an optional one-to-one relation to the User model via the
userfield - Allows staff profiles to be linked to user accounts for login access
2. Staff CRUD Operations
- Status: ✅ Complete
- Full CRUD operations for Staff members via:
- REST API endpoints (
/api/organizations/staff/) - UI views (List, Detail, Create, Update)
- Django Admin interface
- REST API endpoints (
3. User Account Creation for Staff
- Status: ✅ Complete
- Ability to create user accounts for staff members
- Auto-generated username format:
first.last(lowercase) - Auto-generated secure random passwords (12 characters)
- Automatic email delivery of credentials
4. User Account Management
- Status: ✅ Complete
- Create User Account: Create a new user account for staff member
- Link User Account: Link an existing user account to a staff member
- Unlink User Account: Remove user account association
- Send Invitation Email: Resend credentials with new password
Implementation Details
Files Created/Modified
Backend Files
-
apps/organizations/services.py(NEW)StaffServiceclass with methods:generate_username(staff)- Generate unique usernamegenerate_password()- Generate secure passwordcreate_user_for_staff(staff, role, request)- Create user accountlink_user_to_staff(staff, user_id, request)- Link existing userunlink_user_from_staff(staff, request)- Unlink user accountsend_credentials_email(staff, password, request)- Send credentials emailget_staff_type_role(staff_type)- Map staff type to role
-
apps/organizations/serializers.py(MODIFIED)- Added
has_user_accountfield to StaffSerializer - Added write-only fields:
create_user,user_username,user_password,send_email - Enhanced
create()method to support optional user account creation - Enhanced
update()method to support optional user account creation
- Added
-
apps/organizations/views.py(MODIFIED)- Added custom actions to StaffViewSet:
create_user_account- POST/api/organizations/staff/{id}/create_user_account/link_user- POST/api/organizations/staff/{id}/link_user/unlink_user- POST/api/organizations/staff/{id}/unlink_user/send_invitation- POST/api/organizations/staff/{id}/send_invitation/
- Added custom actions to StaffViewSet:
-
apps/organizations/admin.py(MODIFIED)- Added
has_user_accountcolumn to list display - Added admin actions:
create_user_accounts- Bulk create user accountssend_credentials_emails- Bulk send credential emails
- Added
-
apps/organizations/forms.py(NEW)StaffFormfor creating and updating staff- Includes RBAC filtering for hospitals and departments
- Validates unique employee IDs
- Cleans and normalizes email addresses
-
apps/organizations/ui_views.py(MODIFIED)staff_detail(pk)- Display staff details with user account statusstaff_create(request)- Create new staff with optional user accountstaff_update(request, pk)- Update staff with optional user account creation
-
apps/organizations/urls.py(MODIFIED)- Added URL patterns:
/staff/create/- Create staff/staff/<uuid:pk>/- Staff detail/staff/<uuid:pk>/edit/- Update staff
- Added URL patterns:
Frontend Files
-
templates/organizations/staff_list.html(NEW)- Staff list with filtering and search
- User account status indicators
- Actions for creating/sending/unlinking user accounts
- Pagination support
- Confirmation modals for user account actions
-
templates/organizations/staff_detail.html(NEW)- Detailed staff profile view
- User account status display
- User account management actions
- Confirmation modals
-
templates/organizations/staff_form.html(NEW)- Staff creation/editing form
- Optional user account creation checkbox
- Tips and guidance for users
-
templates/organizations/emails/staff_credentials.html(NEW)- Professional email template for credentials
- Contains username, password, and login URL
- Security notice about password change
- Responsive design
-
templates/layouts/partials/sidebar.html(MODIFIED)- Added "Staff" menu item with icon
- Positioned between "Physicians" and "Complaints"
User Account Creation Process
Username Generation
- Format:
first.last(all lowercase) - Example: John Smith →
john.smith - Duplicate handling: Appends number if duplicate exists
john.smith2,john.smith3, etc.
Password Generation
- Length: 12 characters
- Characters: Letters, numbers, and special characters
- Generated using
secretsmodule for cryptographic security
Role Assignment
- All staff types receive the
staffrole by default - Can be modified by admins if needed
- Mapping: physician → staff, nurse → staff, admin → staff, other → staff
Email Delivery
- Credentials are sent automatically when user account is created
- Email includes:
- Username
- Password
- Email address
- Login URL
- Staff member is advised to change password after first login
API Endpoints
Staff Management
GET /api/organizations/staff/- List staff (with filters)POST /api/organizations/staff/- Create staff (with optional user account)GET /api/organizations/staff/{id}/- Get staff detailsPUT/PATCH /api/organizations/staff/{id}/- Update staffDELETE /api/organizations/staff/{id}/- Delete staff
User Account Actions
POST /api/organizations/staff/{id}/create_user_account/- Create user accountPOST /api/organizations/staff/{id}/link_user/- Link existing userPOST /api/organizations/staff/{id}/unlink_user/- Unlink user accountPOST /api/organizations/staff/{id}/send_invitation/- Send invitation email
Permissions
Staff Viewing
- PX Admins: Can view all staff
- Hospital Admins: Can view staff in their hospital
- Department Managers: Can view staff in their department
- Others: Can view staff in their hospital
User Account Creation/Management
- PX Admins: Can create/link/unlink user accounts for all staff
- Hospital Admins: Can create/link/unlink user accounts for staff in their hospital only
- Other roles: No permission to manage user accounts
UI Views
Staff List (/staff/)
- Filter by hospital, status, staff type
- Search by name, ID, license, job title
- User account status indicators (Yes/No)
- Quick actions for user account management
- Pagination support
Staff Detail (/staff/{id}/)
- Complete staff profile
- User account status and details
- User account management actions
- Related information (hospital, department, etc.)
Staff Create (/staff/create/)
- Staff information form
- Optional user account creation checkbox
- Hospital/department filtering based on user role
- Email address required for user account creation
Staff Edit (/staff/{id}/edit/)
- Update staff information
- Optional user account creation (if not already created)
Email Configuration
Required Settings
Ensure the following settings are configured in config/settings/base.py:
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'your-smtp-server.com'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = 'your-email@domain.com'
EMAIL_HOST_PASSWORD = 'your-password'
DEFAULT_FROM_EMAIL = 'noreply@px360.local'
Usage Examples
Creating Staff with User Account via API
curl -X POST http://localhost:8000/api/organizations/staff/ \
-H "Content-Type: application/json" \
-H "Authorization: Bearer <token>" \
-d '{
"first_name": "John",
"last_name": "Smith",
"staff_type": "physician",
"job_title": "Cardiologist",
"employee_id": "EMP001",
"email": "john.smith@example.com",
"hospital": "<hospital-uuid>",
"department": "<department-uuid>",
"status": "active",
"create_user": true,
"send_email": true
}'
Creating User Account for Existing Staff via API
curl -X POST http://localhost:8000/api/organizations/staff/<staff-id>/create_user_account/ \
-H "Content-Type: application/json" \
-H "Authorization: Bearer <token>" \
-d '{}'
Audit Logging
All user account management actions are logged:
- User creation events
- User linking/unlinking events
- Email sending events
- Includes metadata: staff ID, staff name, role, etc.
Testing Recommendations
-
Test User Account Creation
- Create staff with email
- Create user account
- Verify email delivery
- Test login with credentials
-
Test User Account Linking
- Create existing user
- Link to staff member
- Verify association
-
Test Permissions
- Test PX Admin can manage all staff
- Test Hospital Admin can only manage hospital staff
- Test other roles cannot manage user accounts
-
Test Email Delivery
- Verify email template rendering
- Test with different email addresses
- Verify login URL is correct
-
Test Edge Cases
- Duplicate usernames
- Staff without email
- Staff already has user account
- Invalid email addresses
Security Considerations
-
Password Security
- Strong random password generation
- Passwords are hashed before storage
- Staff advised to change password after first login
-
Access Control
- RBAC enforced at all levels
- Hospital Admins restricted to their hospital
- API endpoints have permission checks
-
Email Security
- Email sent via secure connection (TLS)
- Password included in email (required for first login)
- Security notice encourages password change
-
Audit Trail
- All actions logged
- Includes user, timestamp, and metadata
- Can be reviewed for security audits
Future Enhancements
Potential improvements for future versions:
-
Two-Factor Authentication
- Add 2FA option for staff accounts
-
Password Policies
- Enforce password complexity rules
- Password expiration policies
-
Bulk User Account Creation
- CSV import for bulk staff with user accounts
- Background job for email sending
-
User Account Status Management
- Ability to deactivate user accounts without unlinking
- Temporarily suspend access
-
Password Reset Flow
- Integration with existing password reset system
- Staff-initiated password reset
Conclusion
The Staff User Account Management feature is fully implemented and ready for use. Staff members can now be given login access to the PX360 system with automatic credential delivery via email. The implementation includes proper RBAC, audit logging, and a user-friendly interface for managing staff user accounts.