Authentication and Authorization DOMAIN - Backend customer, session, and bearer-token auth use cases
Overview
This domain splits authentication into two distinct tracks used by the backend:
- Internal application auth uses
src.usecase.auth to register users, verify passwords with bcrypt, and mint signed JWT bearer tokens.
- Customer-facing API auth uses
src.services.customer_service.CustomerService to create, authenticate, rotate, and deactivate MySQL-backed customer API keys.
The code paths are intentionally different. Internal users are represented by the User domain model and authenticated through password verification plus token issuance. Customers are represented by CustomerModel rows in MySQL, where the plaintext key is shown only at creation time, the hash is persisted, and later requests are accepted only when the stored key hash and active flag match.
Architecture Overview
flowchart TB
subgraph InternalAppAuth[Internal Application Auth]
RegisterUser[register_user]
AuthenticateUser[authenticate_user]
GetPasswordHash[get_password_hash]
VerifyPassword[verify_password]
CreateAccessToken[create_access_token]
UserRepo[UserRepository]
UserModel[User]
end
subgraph CustomerApiKeyAuth[Customer API Key Auth]
CustomerService[CustomerService]
GenerateApiKey[generate_api_key]
HashApiKey[hash_api_key]
VerifyApiKey[verify_api_key]
CustomerModel[CustomerModel]
CustomerSessionAlias[CustomerSessionModel alias]
end
subgraph ExternalSecurity[Security Primitives]
Bcrypt[bcrypt]
JoseJWT[python-jose jwt]
Secrets[secrets]
Sha256[hashlib sha256]
end
subgraph ExternalProvisioning[External Provisioning]
SaltEdgeClient[SaltEdgeClient]
SaltEdgeUsecase[get_or_create_saltedge_customer]
end
RegisterUser --> UserRepo
RegisterUser --> GetPasswordHash
RegisterUser --> SaltEdgeUsecase
AuthenticateUser --> UserRepo
AuthenticateUser --> VerifyPassword
CreateAccessToken --> JoseJWT
GetPasswordHash --> Bcrypt
VerifyPassword --> Bcrypt
CustomerService --> CustomerModel
CustomerService --> GenerateApiKey
CustomerService --> HashApiKey
CustomerService --> VerifyApiKey
GenerateApiKey --> Secrets
HashApiKey --> Sha256
SaltEdgeUsecase --> SaltEdgeClient
UserRepo --> UserModel
CustomerService --> CustomerSessionAlias
Business Layer
src/usecase/auth.py
[!NOTE]
ACCESS_TOKEN_EXPIRE_MINUTES is defined as 30, but create_access_token uses timedelta(minutes=15) when expires_delta is omitted. The constant is not used by the function, so default token lifetime depends on the caller supplying an explicit expiration.
This module contains the internal application authentication logic: password hashing, password verification, JWT creation, user registration, and user login lookup.
Module constants
| Constant |
Type |
Description |
SECRET_KEY |
str |
JWT signing key read from SECRET_KEY, defaulting to "your-secret-key". |
ALGORITHM |
str |
JWT algorithm, fixed to "HS256". |
ACCESS_TOKEN_EXPIRE_MINUTES |
int |
Declared access-token lifetime constant set to 30. |
_BCRYPT_MAX_BYTES |
int |
Maximum password bytes used directly by bcrypt before SHA-256 preprocessing. |
Public functions
| Method |
Description |
_prepare_bcrypt_secret |
Encodes a password as UTF-8 bytes or SHA-256 digest bytes when the UTF-8 input exceeds _BCRYPT_MAX_BYTES. |
get_password_hash |
Hashes a password with bcrypt and returns the encoded hash string. |
verify_password |
Verifies a plaintext password against a stored bcrypt hash and returns True or False. |
create_access_token |
Builds a signed JWT string with an exp claim. |
authenticate_user |
Looks up a user by email, then username fallback, and returns the matching User when the password check succeeds. |
register_user |
Validates uniqueness, hashes the password, persists a new User, and triggers SaltEdge customer provisioning. |
User domain contract used by auth.py
| Property |
Type |
Description |
id |
`int \ |
None` |
username |
str |
Checked for duplicates in register_user and used as a fallback login identifier in authenticate_user. |
email |
str |
Primary identifier for registration checks and login lookup. |
hashed_password |
str |
bcrypt hash persisted on the User. |
role |
str |
Defaults to "applicant" in register_user. |
application_id |
`int \ |
None` |
created_at |
`datetime \ |
None` |
Function behavior
_prepare_bcrypt_secret:
- returns raw UTF-8 bytes for short inputs;
- returns
hashlib.sha256(password_bytes).digest() for long inputs.
get_password_hash:
- calls
bcrypt.hashpw(...) with a generated salt;
- returns the decoded hash string.
verify_password:
- calls
bcrypt.checkpw(...);
- returns
False when bcrypt raises ValueError.
create_access_token:
- copies the provided payload;
- attaches
exp using either the passed expires_delta or a 15-minute default;
- encodes the token with
jwt.encode(..., SECRET_KEY, algorithm=ALGORITHM).
authenticate_user:
- calls
user_repo.get_user_by_email(email);
- falls back to
user_repo.get_user_by_username(email) when the email lookup misses;
- returns
None when the user is missing or the password check fails.
register_user:
- rejects duplicate usernames and emails with
ValueError;
- hashes the password and creates a
User;
- calls
user_repo.create_user(new_user);
- attempts SaltEdge customer creation for
created_user.email;
- swallows SaltEdge configuration and runtime errors after printing a warning.
Registration side effect with SaltEdge
register_user directly instantiates SaltEdgeClient() and calls get_or_create_saltedge_customer(created_user.email, saltedge_client). If SaltEdge provisioning fails, the new user still exists and the function returns the created user.
src/services/customer_service.py
CustomerService is the MySQL-backed customer API-key facade. It manages customer creation, authentication, key rotation, and soft deactivation.
Constructor dependencies
| Type |
Description |
Session |
SQLAlchemy session used for all customer reads and writes. |
Properties
| Property |
Type |
Description |
db |
Session |
The injected SQLAlchemy session stored on the service instance. |
Public methods
| Method |
Description |
create_customer |
Generates a customer id and plaintext API key, stores the hashed key and prefix in MySQL, and returns the new customer id plus plaintext key. |
authenticate |
Verifies a plaintext API key against an active customer row and returns the matching CustomerModel or None. |
rotate_api_key |
Replaces the stored API key hash and prefix for an existing customer and returns the new plaintext key. |
deactivate_customer |
Soft-deletes a customer by setting is_active to False. |
Observed CustomerModel fields used by CustomerService
| Property |
Type |
Description |
customer_id |
str |
Primary customer identifier used for lookup, rotation, and deactivation. |
customer_name |
str |
Display name assigned at customer creation. |
api_key_hash |
str |
SHA-256 hash of the plaintext API key. |
api_key_prefix |
str |
Leading key fragment stored for identification and display. |
is_active |
bool |
Active-state gate used during authentication. |
Customer lifecycle behavior
create_customer:
- calls
generate_api_key();
- hashes the plaintext key with
hash_api_key(...);
- generates a UUID string for
customer_id;
- stores
customer_name, api_key_hash, api_key_prefix, and is_active=True;
- commits the row and returns
(customer_id, api_key).
authenticate:
- rejects empty keys early by returning
None;
- hashes the presented key with
hash_api_key(...);
- queries for a row matching
api_key_hash and is_active is True;
- returns
None when no active row matches;
- calls
verify_api_key(api_key, customer.api_key_hash) as a final check;
- logs a warning on hash mismatch and returns
None.
rotate_api_key:
- loads the customer by
customer_id;
- raises
ValueError when the customer is missing;
- generates and stores a new key hash and prefix;
- commits the update and returns the new plaintext key.
deactivate_customer:
- loads the customer by
customer_id;
- raises
ValueError when the customer is missing;
- sets
is_active = False and commits the change.
src/models/customer.py
This module defines customer API-key helpers and the public key format used by CustomerService.
Module constants
| Constant |
Type |
Description |
API_KEY_PREFIX_LENGTH |
int |
Number of leading characters from the plaintext API key stored in api_key_prefix. |
Public functions
| Method |
Description |
generate_api_key |
Creates a new API key string in the sk_live_... format. |
hash_api_key |
Returns the SHA-256 hex digest of a plaintext API key. |
API key behavior
generate_api_key:
- builds
sk_live_ plus a 32-character slice from secrets.token_urlsafe(32);
- returns the plaintext key only at creation time.
hash_api_key:
- computes
hashlib.sha256(api_key.encode()).hexdigest();
- matches the value persisted by
CustomerService.
verify_api_key:
- is consumed by
CustomerService.authenticate as the final comparison step.
src/models/session.py
This module is a thin export layer for the customer session model used by the MySQL auth domain.
Exported symbol
| Symbol |
Description |
CustomerSessionModel |
Re-export of src.infra.mysql.models.CustomerSessionModel for session persistence code that imports from src.models.session. |
src/usecase/saltedge_usecase.py
This module is not an auth system on its own, but it is part of the registration-side effect used by register_user.
Public functions
| Method |
Description |
get_or_create_saltedge_customer |
Attempts to create a SaltEdge customer for the provided identifier and returns the SaltEdge customer id when available. |
generate_saltedge_connect_url |
Creates a SaltEdge connect session and returns connect metadata when available. |
Auth-domain relevance
register_user calls get_or_create_saltedge_customer(created_user.email, saltedge_client) after local user creation. That makes SaltEdge customer provisioning part of the application-user registration flow, but the registration result still succeeds when SaltEdge provisioning fails.
Feature Flows
Internal user registration and login
sequenceDiagram
participant Caller as Caller
participant Auth as auth py
participant Repo as UserRepository
participant SaltEdge as SaltEdgeClient
participant Jwt as jwt
Caller->>Auth: register_user
Auth->>Repo: get_user_by_username
Auth->>Repo: get_user_by_email
Auth->>Auth: get_password_hash
Auth->>Repo: create_user
Auth->>SaltEdge: create_customer
SaltEdge-->>Auth: customer id or error
Auth-->>Caller: created User
Caller->>Auth: authenticate_user
Auth->>Repo: get_user_by_email
Auth->>Repo: get_user_by_username
Auth->>Auth: verify_password
Auth-->>Caller: User or None
Caller->>Auth: create_access_token
Auth->>Jwt: encode claims
Jwt-->>Auth: signed token
Auth-->>Caller: access token
register_user rejects duplicate usernames and emails before any persistence call.
- A successful registration hashes the password, creates a
User, and persists it through UserRepository.
- After persistence, the function tries to provision a SaltEdge customer for the new email address.
authenticate_user loads by email first, then username fallback, and returns the user only when verify_password succeeds.
create_access_token signs the payload into a JWT bearer token.
Customer API key issuance, verification, rotation, and deactivation
sequenceDiagram
participant Caller as Caller
participant CustomerService as CustomerService
participant Helpers as customer py
participant Db as SQLAlchemy Session
participant Model as CustomerModel
Caller->>CustomerService: create_customer
CustomerService->>Helpers: generate_api_key
CustomerService->>Helpers: hash_api_key
CustomerService->>Db: add and commit CustomerModel
Db-->>CustomerService: persisted row
CustomerService-->>Caller: customer id and plaintext key
Caller->>CustomerService: authenticate
CustomerService->>Helpers: hash_api_key
CustomerService->>Db: query by api_key_hash and is_active
Db-->>CustomerService: CustomerModel or none
CustomerService->>Helpers: verify_api_key
CustomerService-->>Caller: CustomerModel or None
Caller->>CustomerService: rotate_api_key
CustomerService->>Db: load CustomerModel by customer_id
CustomerService->>Helpers: generate_api_key
CustomerService->>Helpers: hash_api_key
CustomerService->>Db: commit update
CustomerService-->>Caller: new plaintext key
Caller->>CustomerService: deactivate_customer
CustomerService->>Db: load CustomerModel by customer_id
CustomerService->>Db: set is_active false and commit
CustomerService-->>Caller: void
Active customer state transitions
stateDiagram-v2
[*] --> Active: create_customer
Active --> Active: rotate_api_key
Active --> Inactive: deactivate_customer
Inactive --> [*]
create_customer initializes the customer as active.
rotate_api_key keeps the customer active while replacing the secret.
deactivate_customer moves the row out of the authenticated set by clearing is_active.
State Management
Authentication state patterns
- Internal users
- persistence is delegated to
UserRepository;
register_user enforces uniqueness before create;
- password state is stored only as
hashed_password;
- bearer token state is encoded into JWT
exp claims.
- Customers
- authentication state is persisted in MySQL through
CustomerModel;
is_active gates acceptance during authenticate;
rotate_api_key replaces the stored secret without changing the customer identity;
deactivate_customer preserves the row while removing access.
Session model surface
src/models/session.py exposes CustomerSessionModel from the MySQL model layer. That makes the customer-session type available through the auth-domain import path without adding new behavior in this module.
Error Handling
Internal application auth
| Function |
Failure condition |
Behavior |
register_user |
Existing username |
Raises ValueError("Username already registered"). |
register_user |
Existing email |
Raises ValueError("Email already registered"). |
authenticate_user |
No user or password mismatch |
Returns None. |
verify_password |
bcrypt raises ValueError |
Returns False. |
Customer API-key auth
| Method |
Failure condition |
Behavior |
authenticate |
Empty API key |
Returns None. |
authenticate |
No active row matches |
Returns None. |
authenticate |
Final secret comparison fails |
Logs a warning and returns None. |
rotate_api_key |
Customer not found |
Raises ValueError(f"Customer {customer_id} not found"). |
deactivate_customer |
Customer not found |
Raises ValueError(f"Customer {customer_id} not found"). |
Dependencies
Security and crypto libraries
bcrypt for password hashing and verification.
jose.jwt and JWTError for JWT bearer token creation and verification support.
hashlib for SHA-256 password preprocessing and API key hashing.
secrets for API key generation.
Persistence and domain contracts
sqlalchemy.orm.Session for customer persistence.
src.domain.user.User and UserRepository for internal application auth.
src.infra.mysql.models.CustomerModel for customer API-key persistence.
src.infra.mysql.models.CustomerSessionModel exposed through src.models.session.
External provisioning
SaltEdgeClient
SaltEdgeConfigurationError
get_or_create_saltedge_customer
register_user uses these dependencies to provision a SaltEdge customer record after local user creation.
Testing Considerations
Unit coverage in backend/tests/usecase/test_auth.py
MockUserRepository
| Property / Method |
Type |
Description |
users |
dict |
In-memory map keyed by email for test users. |
create_user |
Method |
Assigns an id, stamps created_at, stores the user, and returns it. |
get_user_by_email |
Method |
Returns a stored user by email. |
get_user_by_username |
Method |
Searches stored users for a matching username. |
Test functions
| Test |
What it validates |
test_password_hashing |
get_password_hash and verify_password accept a correct password and reject an incorrect one. |
test_register_user |
Registration creates a user, persists a bcrypt hash, and rejects duplicate email and username. |
test_authenticate_user |
Login succeeds with the registered password and returns None for wrong or missing users. |
Customer API-key coverage in backend/tests/test_auth.py
| Test |
What it validates |
_create_session |
Builds an in-memory SQLite session and creates the metadata schema for auth tests. |
test_hash_and_verify_api_key |
generate_api_key, hash_api_key, and verify_api_key work together for valid and invalid keys. |
test_customer_service_authenticate |
CustomerService.create_customer returns a usable API key and authenticate resolves the persisted customer. |
Auth endpoint behavior in backend/tests/interface/test_auth_endpoints.py
These tests confirm the HTTP-facing auth flow exercised by the backend interface:
- registration returns a user payload with
id, username, email, and role;
- token login returns a bearer token payload with
token_type, role, user, and access_token;
- the bearer token works for a follow-up authenticated profile request;
- admin and realtor overrides affect the returned role;
- override parsing normalizes quotes and whitespace;
- default realtor and admin override sets contain the expected addresses.
Test database and client fixtures
backend/tests/conftest.py
| Fixture / Function |
Type |
Description |
client |
Fixture |
Overrides get_db, seeds an admin account, logs in, and preloads an Authorization: Bearer ... header for interface tests. |
backend/tests/infra/mysql/test_user_repository.py
| Fixture / Function |
Type |
Description |
db_session |
Fixture |
Creates a SQLite in-memory SQLAlchemy session for repository tests. |
user_repository |
Fixture |
Returns a SQLAlchemyUserRepository bound to the test session. |
Key Classes Reference
| Class |
Responsibility |
auth.py |
Internal application password hashing, user registration, user authentication, and JWT issuance. |
customer_service.py |
Customer API-key creation, authentication, rotation, and soft deactivation. |
customer.py |
API key generation and SHA-256 hashing helpers. |
session.py |
Re-export of the MySQL customer session model. |
test_auth.py |
Unit tests for password hashing, user registration, and user authentication. |
test_auth_endpoints.py |
Interface tests covering registration, token login, profile access, and role overrides. |