Authentication
The Authentication module provides secure access control for the UBU Digital Finance Solution, implementing multiple layers of security to protect user accounts and system resources.
Overview
This module handles all aspects of user authentication and session management, including:
- User login with username/password
- Two-factor authentication (2FA)
- JWT token-based session management
- Password reset and change functionality
- Role-based access control
Features
User Authentication Flow
The system supports a flexible authentication flow:
- Basic Authentication: Username (user code) and password verification
- Two-Factor Authentication (optional): OTP verification after successful password authentication
- Token Generation: Access and refresh tokens are issued after successful authentication
- Session Management: Active sessions are tracked and can be terminated
JWT Token Authentication
The system uses JSON Web Tokens (JWT) for authentication:
- Access Tokens: Short-lived tokens (30 minutes) used for API authorization
- Refresh Tokens: Long-lived tokens (7 days) used to obtain new access tokens
- Token Payload: Contains user ID, user code, and active status
Two-Factor Authentication (2FA)
For enhanced security, the system supports optional two-factor authentication:
- After successful password verification, an OTP is generated and sent to the user's email
- The OTP is valid for a limited time (3 minutes)
- The user must enter the OTP to complete the authentication process
- Users can enable or disable 2FA for their accounts
Password Management
The system provides comprehensive password management features:
- Password Reset: Administrators can reset user passwords, generating a new temporary password
- Password Change: Users can change their passwords by providing their current password
- Password Security: All passwords are hashed using bcrypt before storage
Session Management
User sessions are managed securely:
- Each login creates a new session with unique tokens
- Sessions can be terminated by administrators
- Refresh tokens can be used to obtain new access tokens without re-authentication
- Token validation includes checking user active status
API Endpoints
| Endpoint | Method | Description |
|---|---|---|
/authentication/request-otp |
POST | Request OTP after username/password verification |
/authentication/resend-otp |
POST | Resend OTP if expired |
/authentication/verify-otp |
POST | Verify OTP and generate tokens |
/authentication/refresh-token |
POST | Get new access token using refresh token |
/authentication/reset-password/{user_id} |
POST | Reset a user's password |
/authentication/change-password |
PUT | Change current user's password |
Implementation Details
Token Generation
Access and refresh tokens are generated using the following process:
- Create a payload containing user information
- Set an expiration time based on token type
- Sign the token using a secret key and the HS256 algorithm
def create_token(data: dict, expires_delta: timedelta = None, token_type: str = 'access'):
to_encode = data.copy()
if expires_delta:
expire = datetime.utcnow() + expires_delta
else:
if token_type == 'access':
expire = datetime.utcnow() + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
else:
expire = datetime.utcnow() + timedelta(days=REFRESH_TOKEN_EXPIRE_DAYS)
to_encode.update({"exp": expire, "type": token_type})
encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
return encoded_jwt
OTP Generation and Verification
One-time passwords are generated and verified as follows:
- Generate a random 6-digit OTP
- Store the OTP and its expiration time in the user record
- Send the OTP to the user's email
- Verify the provided OTP against the stored value and check expiration
Token Validation
Tokens are validated using the following process:
- Decode the JWT token using the secret key
- Verify the token has not expired
- Extract the user information from the token payload
- Check that the user account is active
Permission-Based Authorization
The system implements a flexible permission-based authorization system:
- Each endpoint is protected by a permission check
- The user's roles are retrieved from the database
- The permissions associated with those roles are retrieved
- The required permission is checked against the user's permissions
Planned Security Enhancements
The following security enhancements are planned for future implementation:
- Rate limiting and login throttling
- Login attempt tracking and account lockout
- IP whitelisting
- Advanced logout functionality
- Monitoring, logging, and alerting for security events