Authentication and Authorization Domain - Backend Customer, Session, and Auth Use Cases

Overview

This backend domain covers two separate access patterns used across the platform:

  • User authentication for account registration, sign-in, and bearer-token profile lookup.
  • Customer API key authentication for service-to-service access, where the customer secret is only shown once and the persisted record keeps a hash plus a prefix.

The same domain also connects to downstream consent enforcement. CustomerModel identifies the tenant/customer, CustomerSessionModel exposes the session record type used by the backend model layer, and ConsentGrantModel is the consent gate that the applicant workflow checks before it creates access-bearing records.

The user-facing result is a login flow that returns a JWT-style access token, while internal platform calls use customer API keys and consent grants to control which records can be created or read. The tests in this section show the full round-trip for registration, login, /api/auth/me, API-key authentication, and consent validation.

Architecture Overview

flowchart TB
    subgraph AuthUseCases[Authentication Use Cases]
        RegisterUser[register_user]
        AuthenticateUser[authenticate_user]
        VerifyPassword[verify_password]
        GetPasswordHash[get_password_hash]
        CreateAccessToken[create_access_token]
    end

    subgraph CustomerAuth[Customer API Key Service]
        CustomerService[CustomerService]
        GenerateApiKey[generate_api_key]
        HashApiKey[hash_api_key]
        VerifyApiKey[verify_api_key]
        CustomerModel[CustomerModel]
        CustomerSessionModel[CustomerSessionModel]
    end

    subgraph ConsentAccess[Consent Access Control]
        ConsentGrantModel[ConsentGrantModel]
        ApplicantService[ApplicantService create_applicant]
    end

    subgraph ExternalSystems[External Systems]
        SaltEdgeClient[SaltEdgeClient]
        JwtLib[jose jwt]
        BcryptLib[bcrypt]
    end

    ApiClient[API Client] --> RegisterUser
    ApiClient --> AuthenticateUser
    ApiClient --> CustomerService

    RegisterUser --> GetPasswordHash
    AuthenticateUser --> VerifyPassword
    CreateAccessToken --> JwtLib
    VerifyPassword --> BcryptLib
    GetPasswordHash --> BcryptLib

    RegisterUser --> SaltEdgeClient
    RegisterUser --> UserRepository[UserRepository]
    AuthenticateUser --> UserRepository

    CustomerService --> GenerateApiKey
    CustomerService --> HashApiKey
    CustomerService --> VerifyApiKey
    CustomerService --> CustomerModel
    CustomerService --> CustomerSessionModel

    ApplicantService --> ConsentGrantModel
    ConsentGrantModel --> CustomerModel

Business Layer

src/usecase/auth.py

backend/src/usecase/auth.py

The auth use cases handle local user registration, password verification, JWT issuance, and sign-in by email or username. The registration flow also attempts to provision a SaltEdge customer record after the local user is created.

Module constants

Name Description
SECRET_KEY JWT signing key read from the SECRET_KEY environment variable, with your-secret-key as the fallback.
ALGORITHM JWT algorithm used by create_access_token; set to HS256.
ACCESS_TOKEN_EXPIRE_MINUTES Module-level token lifetime constant set to 30.
_BCRYPT_MAX_BYTES Maximum password byte length passed directly to bcrypt before SHA-256 pre-hashing is used.

Public methods

Method Description
register_user Checks duplicate username and email, hashes the password, creates a User, and attempts SaltEdge customer provisioning for the created email.
authenticate_user Looks up a user by email first, then username, and returns the user only when the password matches.
verify_password Verifies a plaintext password against a stored bcrypt hash and returns False on bcrypt errors.
get_password_hash Produces a bcrypt hash for a plaintext password using the module’s password preparation logic.
create_access_token Signs a JWT payload, adds an exp claim, and returns the encoded token string.

User object fields created by register_user

Field Type Description
id None on construction Left unset before repository persistence assigns the identifier.
username str Unique login name stored on the user record.
email str User email used for login fallback and profile lookup.
hashed_password str bcrypt hash produced by get_password_hash.
role str Role assigned during registration; defaults to applicant.
application_id `int \ None`

Password handling

get_password_hash calls bcrypt with a prepared secret, and _prepare_bcrypt_secret hashes overlong inputs with SHA-256 before bcrypt sees them. verify_password uses bcrypt.checkpw and converts bcrypt ValueError failures into False, which keeps bad or malformed hashes from raising through the authentication flow.

src/services/customer_service.py

[!NOTE] register_user creates the local user first and then attempts SaltEdge customer provisioning. If SaltEdge is not configured or any exception occurs, the registration still returns the created local user. [!NOTE] authenticate_user accepts either an email or a username in its email argument: it queries by email first and then falls back to username.

backend/src/services/customer_service.py

CustomerService manages customer API keys in the MySQL-backed customer table. It creates the customer record, authenticates plaintext API keys against hashed storage, rotates keys, and soft-deactivates customers.

Constructor dependencies

Type Description
Session SQLAlchemy session used to persist and query CustomerModel rows.

Properties

Property Type Description
db Session Active SQLAlchemy session stored on the service instance.

Public methods

Method Description
create_customer Creates a new active customer, stores only the API key hash and prefix, and returns the customer_id plus plaintext API key.
authenticate Validates a plaintext API key against an active customer row and returns the matching CustomerModel or None.
rotate_api_key Generates and persists a new API key for an existing customer, replacing the stored hash and prefix.
deactivate_customer Soft-deletes a customer by setting is_active to False and committing the change.

Customer creation and authentication flow

create_customer generates a plaintext key, hashes it, assigns a UUID-based customer_id, and persists CustomerModel with is_active=True. authenticate re-hashes the presented plaintext key, filters by api_key_hash and is_active, then runs verify_api_key against the row that was returned.

src/models/customer.py

[!NOTE] authenticate only returns a customer when the row is active and the stored hash matches the presented key. The service logs a warning before returning None when verify_api_key does not validate the stored record.

backend/src/models/customer.py

This module is the customer API key utility layer. It defines the prefix length used in customer records and exposes the helper functions used by CustomerService and the tests.

Module constants

Name Description
API_KEY_PREFIX_LENGTH Number of characters from the plaintext API key copied into api_key_prefix; set to 8.

Public methods

Method Description
generate_api_key Produces a new plaintext API key for customer onboarding or rotation.
hash_api_key Produces the stored hash representation for a plaintext API key.
verify_api_key Compares a plaintext API key to the stored hash representation.

Customer record fields used in this domain

Field Type Description
customer_id str Stable customer identifier generated by the service.
customer_name str Display name written during customer creation.
api_key_hash str Hashed customer secret persisted instead of the plaintext key.
api_key_prefix str First API_KEY_PREFIX_LENGTH characters of the plaintext key for record identification.
is_active bool Soft-delete flag used by CustomerService.authenticate.

src/models/session.py

backend/src/models/session.py

This module re-exports CustomerSessionModel from src.infra.mysql.models. The domain layer uses it as the canonical session record type for customer session persistence.

Authorization Data Alignment

Model Purpose Alignment in this domain
CustomerModel Stores the tenant/customer identity plus hashed API credentials. Used by CustomerService to create, authenticate, rotate, and deactivate customer API keys.
CustomerSessionModel Session record type re-exported by the domain layer. Exposed for session persistence in the customer/session model layer.
ConsentGrantModel Consent gate for downstream applicant access. Checked by ApplicantService.create_applicant before applicant creation is allowed.

ApplicantService.create_applicant enforces the consent-access boundary by querying ConsentGrantModel with grant_id, customer_id, is_active, and revoked_at is None. If the consent grant is missing or inactive, it raises ValueError("Consent grant is invalid or inactive").

The tests show that this gate is what links authenticated customer identity to data-access authorization: the customer must exist, the API key must authenticate, and the consent grant must still be active before applicant data can be created.

API Integration

Register User

Register User

{
    "title": "Register User",
    "description": "Creates a new user account after validating username and email uniqueness and hashing the password",
    "method": "POST",
    "baseUrl": "<BackendApiBaseUrl>",
    "endpoint": "/api/auth/register",
    "headers": [
        {
            "key": "Content-Type",
            "value": "application/json",
            "required": true
        },
        {
            "key": "Accept",
            "value": "application/json",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "json",
    "requestBody": "{\n    \"username\": \"applicant-user\",\n    \"email\": \"[email protected]\",\n    \"password\": \"pass12345\"\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"id\": 1,\n    \"username\": \"applicant-user\",\n    \"email\": \"[email protected]\",\n    \"role\": \"applicant\"\n}"
        }
    }
}

Login and Issue Access Token

Login and Issue Access Token

{
    "title": "Login and Issue Access Token",
    "description": "Authenticates a user by email or username, then returns a bearer token payload with the user profile and role",
    "method": "POST",
    "baseUrl": "<BackendApiBaseUrl>",
    "endpoint": "/api/auth/token",
    "headers": [
        {
            "key": "Content-Type",
            "value": "application/x-www-form-urlencoded",
            "required": true
        },
        {
            "key": "Accept",
            "value": "application/json",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "formData",
    "requestBody": "{\n    \"username\": \"[email protected]\",\n    \"password\": \"pass12345\"\n}",
    "formData": [
        {
            "key": "username",
            "value": "[email protected]",
            "required": true
        },
        {
            "key": "password",
            "value": "pass12345",
            "required": true
        }
    ],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"access_token\": \"eyJhbGciOiJIUzI1NiIs...\",\n    \"token_type\": \"bearer\",\n    \"role\": \"applicant\",\n    \"user\": {\n        \"id\": 1,\n        \"username\": \"applicant-user\",\n        \"email\": \"[email protected]\",\n        \"role\": \"applicant\"\n    }\n}"
        }
    }
}

Get Current User

Get Current User

{
    "title": "Get Current User",
    "description": "Returns the authenticated user profile from the bearer access token",
    "method": "GET",
    "baseUrl": "<BackendApiBaseUrl>",
    "endpoint": "/api/auth/me",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        },
        {
            "key": "Accept",
            "value": "application/json",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"id\": 1,\n    \"username\": \"applicant-user\",\n    \"email\": \"[email protected]\",\n    \"role\": \"applicant\"\n}"
        }
    }
}

Feature Flows

Registration and Login

sequenceDiagram
    participant C as API Client
    participant A as Auth Endpoint
    participant U as register_user
    participant R as UserRepository
    participant P as get_password_hash
    participant S as SaltEdgeClient
    participant V as authenticate_user
    participant W as verify_password
    participant T as create_access_token

    C->>A: POST /api/auth/register
    A->>U: register_user
    U->>R: get_user_by_username
    U->>R: get_user_by_email
    U->>P: get_password_hash
    U->>R: create_user
    U->>S: create_customer
    A-->>C: created user

    C->>A: POST /api/auth/token
    A->>V: authenticate_user
    V->>R: get_user_by_email
    V->>R: get_user_by_username
    V->>W: verify_password
    A->>T: create_access_token
    A-->>C: access token payload

    C->>A: GET /api/auth/me
    A-->>C: user profile from bearer token

Customer API Key Lifecycle

sequenceDiagram
    participant C as API Client
    participant S as CustomerService
    participant G as generate_api_key
    participant H as hash_api_key
    participant V as verify_api_key
    participant D as Session
    participant M as CustomerModel

    C->>S: create_customer
    S->>G: generate_api_key
    S->>H: hash_api_key
    S->>D: add CustomerModel
    S->>D: commit
    S-->>C: customer_id and plaintext api key

    C->>S: authenticate
    S->>H: hash_api_key
    S->>D: query CustomerModel
    S->>V: verify_api_key
    S-->>C: CustomerModel or None

    C->>S: rotate_api_key
    S->>G: generate_api_key
    S->>H: hash_api_key
    S->>D: update CustomerModel
    S->>D: commit
    S-->>C: new plaintext api key

    C->>S: deactivate_customer
    S->>D: set is_active false
    S->>D: commit
    S-->>C: customer disabled

Error Handling

Function or Service Failure condition Observed behavior
register_user Duplicate username Raises ValueError("Username already registered").
register_user Duplicate email Raises ValueError("Email already registered").
register_user SaltEdge misconfiguration or runtime exception Logs the failure with print and still returns the created local user.
authenticate_user No user found or password mismatch Returns None.
verify_password bcrypt raises ValueError Returns False.
CustomerService.authenticate Empty API key Returns None.
CustomerService.authenticate No matching active customer or key mismatch Returns None.
CustomerService.rotate_api_key Customer not found Raises ValueError(f"Customer {customer_id} not found").
CustomerService.deactivate_customer Customer not found Raises ValueError(f"Customer {customer_id} not found").

Testing Considerations

backend/tests/usecase/test_auth.py

[!NOTE] register_user does not fail user creation when SaltEdge provisioning fails. The local auth identity is authoritative even when the external customer record is unavailable.

  • Verifies get_password_hash and verify_password with a known password and a wrong-password negative check.
  • Verifies register_user creates a user with a bcrypt-hashed password.
  • Verifies authenticate_user succeeds with the registered password and returns None for bad credentials or missing users.

backend/tests/test_auth.py

  • Creates an in-memory SQLite database with Base.metadata.create_all.
  • Instantiates CustomerService and verifies:
    • create_customer returns a generated customer_id and plaintext API key.
    • authenticate accepts the plaintext API key and returns the correct customer.
    • authenticate returns None for an invalid key.

backend/tests/interface/test_auth_endpoints.py

  • Confirms /api/auth/register returns a user object with id, username, email, and role.
  • Confirms /api/auth/token returns:
    • token_type: bearer
    • the expected role
    • a nested user object
    • a bearer access_token
  • Confirms /api/auth/me returns the authenticated profile when the Authorization header is present.
  • Confirms the role override behavior used by the auth endpoints:
    • default admin accounts resolve to admin
    • default realtor accounts resolve to realtor
    • override lists are normalized by stripping quotes and whitespace.

backend/tests/test_applicants.py

  • Shows the broader authorization boundary enforced by customer API keys and consent grants:
    • invalid API keys produce a 401
    • the response includes detail: "Invalid API key" and error_code: "AUTH_INVALID_KEY"
    • a valid customer plus active consent grant allows applicant creation
    • an invalid or inactive consent grant is rejected with 400

Key Classes Reference

Class Responsibility
auth.py Local user registration, password hashing, password verification, and JWT creation.
customer.py Customer API key generation, hashing, verification, and prefix constants.
session.py Domain alias exposing CustomerSessionModel for persisted customer sessions.
customer_service.py Customer creation, API key authentication, rotation, and deactivation.
test_auth.py Integration coverage for customer API key creation and authentication.
test_auth.py Unit coverage for password hashing and user registration/authentication.
test_auth_endpoints.py HTTP-level coverage for register, token, me, and role override behavior.