User & Identity Management
Overview
This feature governs the application's security foundation, managing the complete user identity lifecycle. It provides robust user registration and onboarding, ensuring new accounts are created securely with unique credentials. For existing users, it facilitates secure sign-in through a token-based authentication system, granting temporary access to protected resources. The feature also includes comprehensive password management, allowing users to securely recover access via email-verified tokens and change their passwords. This ensures a trusted and reliable experience for all user interactions, forming the cornerstone of platform security and protecting both user data and system integrity from unauthorized access.
Feature Flow
Use Cases
| Use Case | Trigger | Outcome | Description | Layers |
|---|---|---|---|---|
| User Registration & Onboarding | API call to /signup with user details. | A new user account is created, a welcome email is sent, and an access token is issued. | A new user submits their details via an API call. The system validates the information, creates a new user account, sends a welcome email, and returns an access token. |
API Gateway LayerService LayerUtility LayerRepository Layer
|
| Secure Authentication | API call to /signin with user credentials. | A time-limited access token is issued for the authenticated user. | An existing user provides their credentials through an API call. The system verifies the credentials against stored records, and upon success, issues a time-limited JSON Web Token for session access. |
API Gateway LayerService LayerUtility LayerRepository Layer
|
| Password Management | API call to /forgot-password, /reset-password, or /change-password. | The user's password is securely updated. | A user can request a password reset link via email, use a secure token to set a new password, or change their current password while authenticated, ensuring account security. |
API Gateway LayerService LayerUtility LayerRepository Layer
|
User Registration & Onboarding
Secure Authentication
Password Management
Architecture
Components
| File | Layer | Role | Responsibility |
|---|---|---|---|
auth.py |
API Gateway Layer | Handles user identity routes | Manages API endpoints for user registration, sign-in, and password recovery, orchestrating user services and security functions to ensure a secure and complete identity lifecycle management process for users. |
security.py |
Utility Layer | Provides core security functions | Centralizes security primitives, including password hashing, JWT generation, and token validation. It ensures robust cryptographic protection for all authentication and authorization processes, safeguarding user credentials and session integrity. |
Call Flow
Business Rules
| Rule | Description | Entities |
|---|---|---|
| EmailAlreadyRegistered | Ensures that a new user cannot register with an email address already present in the system. This rule prevents duplicate accounts and maintains unique user identity data integrity. |
User
|
| UsernameAlreadyTaken | Prevents new user registration if the chosen username is already in use by another account. This rule enforces unique user identification and avoids confusion within the platform. |
User
|
| InvalidCredentials | Verifies that the provided email and password combination matches an active user account for successful sign-in. This rule is the primary defense against unauthorized brute-force access attempts. |
UserCredentials
|
| InactiveUserAccount | Prevents inactive user accounts from signing in, ensuring only users with an active status can access the system. This rule enforces account lifecycle policies and enhances security. |
User
|
| InvalidOrExpiredPasswordResetToken | Validates the integrity and time-based validity of a password reset token before allowing a password change. This rule prevents unauthorized password resets using old or tampered tokens. |
PasswordResetToken
|
| IncorrectCurrentPassword | Requires users to provide their correct current password before allowing them to set a new one. This rule adds an extra layer of security for authenticated password changes. |
UserPassword
|
| AccessTokenExpiration | Access tokens must expire after a predefined duration, typically configured in application settings. This rule limits the window of opportunity for token misuse if one is ever compromised. |
AccessToken
|
| PasswordResetTokenExpiration | Password reset tokens must expire within a specific timeframe, usually 24 hours. This rule prevents indefinite validity, reducing the risk of unauthorized password changes from old links. |
PasswordResetToken
|
| PasswordResetTokenTypeValidation | Password reset tokens must explicitly contain a `type` claim indicating their purpose. This rule ensures tokens are used only for their intended function, preventing cross-purpose token exploitation. |
PasswordResetToken
|
| InvalidCredentialsRejection | Any invalid, expired, or malformed authentication credentials must result in an unauthorized access response. This rule enforces strict access control, protecting all secured system resources from intrusion. |
AccessTokenUser
|
| AccessTokenValidityPeriod | Determines the duration for which generated access tokens remain valid, directly influencing session longevity and security. This configuration-driven rule balances user convenience against potential security exposure from long-lived tokens. |
AccessToken
|
Domain Model
| Entity | Type | Description |
|---|---|---|
| User | aggregate_root |
Represents an individual with an account on the platform. It is the central entity for identity, holding credentials, profile information, and status, acting as an aggregate root for authentication. |
| AccessToken | value_object |
A time-limited credential issued upon successful authentication. This value object grants the bearer access to protected resources without re-exposing their primary credentials, representing a temporary session. |
| PasswordResetToken | value_object |
A single-use, time-limited credential for securely verifying a password reset request. This value object ensures that only the legitimate account owner can complete the password recovery process. |
| Credentials | value_object |
A value object representing the combination of a user's identifier (email or username) and password. It is used exclusively for the authentication process to verify a user's identity. |
| Password | value_object |
A value object representing a user's secret authentication key. It is always handled in a hashed format for security and is never stored or transmitted in plain text. |
Integration Points
| System | Type | Usage |
|---|---|---|
| Database | database |
Used for persisting and retrieving all user account information, including hashed passwords and profile details. It is the authoritative source of truth for user identity and status data. |
| Email Service | api |
Utilized to send transactional emails for critical user lifecycle events, such as sending welcome messages upon registration and delivering secure links for password recovery, enhancing user communication and security. |
| Logging System | other |
Captures significant events and errors during authentication and user management processes. It provides essential operational visibility for monitoring security, debugging issues, and auditing user access patterns. |
Configuration
| Key | Impact |
|---|---|
ACCESS_TOKEN_EXPIRE_MINUTES |
This key determines the duration for which generated access tokens remain valid, directly influencing session longevity and security. |
ALGORITHM |
Specifies the cryptographic algorithm used for JWT signing, ensuring consistent and secure token encoding and decoding. |
SECRET_KEY |
Provides the cryptographic key used for signing and verifying all JWTs, crucial for token integrity and authenticity. |
Glossary
| Term | Definition |
|---|---|
access_token |
A credential issued upon successful authentication, granting temporary, authorized access to protected resources within the application. |
change_password |
The action of an authenticated user updating their existing password to a new one, requiring current password verification. |
expire |
The specific timestamp when a token's validity ends, after which it can no longer be used for authentication. |
forgot_password |
The process initiated by a user who cannot recall their password, requesting a mechanism to regain account access. |
hash_password |
The process of converting a plain text password into an irreversible, fixed-length string for secure storage. |
password_reset_token |
A unique, time-limited string used to securely verify a password reset request, ensuring only authorized resets occur. |
payload |
The data section within a JSON Web Token, containing claims or information about the authenticated user or token purpose. |
reset_password |
The action of setting a new password after a successful `forgot_password` request, typically using a verified token. |
signin |
The process of an existing user logging into the system by providing their credentials to gain authenticated access. |
signup |
The process of a new user creating an account within the system, providing initial registration details and credentials. |
token_response |
The structured data returned after successful authentication, including the access token and user details. |
user_create |
The data structure containing information required to register a new user, including email, username, and password. |
user_signin |
The data structure containing credentials for user authentication, typically an email or username and a password. |
verify_password |
The action of comparing a plain text password against its stored hash to confirm user identity. |
FAQs
Why are UserService and email_service injected rather than instantiated directly?
Dependency injection promotes loose coupling and testability by allowing external services to be provided at runtime. This design facilitates easier mocking during testing and flexible service configuration.
What is the purpose of using Pydantic schemas for request and response bodies?
Pydantic schemas provide robust data validation and serialization, ensuring that incoming request data conforms to expected structures and outgoing responses are consistently formatted. This enhances API reliability.
Why is bcrypt chosen for password hashing in this module?
The bcrypt algorithm is selected for password hashing due to its strong resistance against brute-force attacks and its adaptive nature. It provides a secure, industry-standard method for protecting user credentials effectively.
What is the rationale behind setting a short expiration for access tokens?
Access tokens are designed with a short expiration to minimize the window of opportunity for token misuse if compromised. This strategy enhances overall security by requiring frequent re-authentication or token refresh.
How does the system ensure that password reset tokens are secure and time-limited?
Password reset tokens are cryptographically signed and include an expiration timestamp. The verify_password_reset_token function validates both the signature and the expiration, preventing token reuse or tampering.
How does the system ensure password reset tokens are used only for their intended purpose?
Password reset tokens include a specific type claim ("password_reset") within their payload. This claim is explicitly verified during token processing, ensuring tokens are used solely for password reset operations.