Skip to content

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:

  1. Basic Authentication: Username (user code) and password verification
  2. Two-Factor Authentication (optional): OTP verification after successful password authentication
  3. Token Generation: Access and refresh tokens are issued after successful authentication
  4. 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:

  1. After successful password verification, an OTP is generated and sent to the user's email
  2. The OTP is valid for a limited time (3 minutes)
  3. The user must enter the OTP to complete the authentication process
  4. 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:

  1. Create a payload containing user information
  2. Set an expiration time based on token type
  3. 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:

  1. Generate a random 6-digit OTP
  2. Store the OTP and its expiration time in the user record
  3. Send the OTP to the user's email
  4. Verify the provided OTP against the stored value and check expiration

Token Validation

Tokens are validated using the following process:

  1. Decode the JWT token using the secret key
  2. Verify the token has not expired
  3. Extract the user information from the token payload
  4. Check that the user account is active

Permission-Based Authorization

The system implements a flexible permission-based authorization system:

  1. Each endpoint is protected by a permission check
  2. The user's roles are retrieved from the database
  3. The permissions associated with those roles are retrieved
  4. 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