Skip to content

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

Feature Flow Feature Flow API Gateway LayerService & Utility Layersauth.pyUserServiceUserServiceUserServicesecurity.pysecurity.pysecurity.pysecurity.pyUserauth.pyUserServicesecurity.pyEmailServiceDatabaseUserUserauth.pyauth.pyUserServiceUserServicesecurity.pysecurity.pyEmailServiceEmailServiceDatabaseDatabaseauth.pyUserServiceUserServiceUserServicesecurity.pysecurity.pysecurity.pysecurity.pyPOST /signup (details)alt[User Registration & Onboarding]createUser(details)save(user)user_objectsendWelcomeEmail(user)createAccessToken(user_id)access_token{access_token, user_details}[Secure Authentication]POST /signin (credentials)authenticateUser(credentials)findUserByEmail(email)verifyPassword(plain, hashed)user_objectcreateAccessToken(user_id)access_token{access_token, user_details}[Password Management]POST /forgot-password (email)createPasswordResetToken(email)reset_tokensendPasswordResetEmail(email, token)Success MessagePOST /reset-password (token, new_pass)verifyPasswordResetToken(token)user_idupdatePassword(user_id, new_pass)save(user)Success MessageBLOGR - Backend - Feature: User & Identity Management    This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.
Feature Flow Feature Flow API Gateway LayerService & Utility Layersauth.pyUserServiceUserServiceUserServicesecurity.pysecurity.pysecurity.pysecurity.pyUserauth.pyUserServicesecurity.pyEmailServiceDatabaseUserUserauth.pyauth.pyUserServiceUserServicesecurity.pysecurity.pyEmailServiceEmailServiceDatabaseDatabaseauth.pyUserServiceUserServiceUserServicesecurity.pysecurity.pysecurity.pysecurity.pyPOST /signup (details)alt[User Registration & Onboarding]createUser(details)save(user)user_objectsendWelcomeEmail(user)createAccessToken(user_id)access_token{access_token, user_details}[Secure Authentication]POST /signin (credentials)authenticateUser(credentials)findUserByEmail(email)verifyPassword(plain, hashed)user_objectcreateAccessToken(user_id)access_token{access_token, user_details}[Password Management]POST /forgot-password (email)createPasswordResetToken(email)reset_tokensendPasswordResetEmail(email, token)Success MessagePOST /reset-password (token, new_pass)verifyPasswordResetToken(token)user_idupdatePassword(user_id, new_pass)save(user)Success MessageBLOGR - Backend - Feature: User & Identity Management    This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.

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 Layer
Service Layer
Utility Layer
Repository 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 Layer
Service Layer
Utility Layer
Repository 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 Layer
Service Layer
Utility Layer
Repository Layer

User Registration & Onboarding

Use Case - User Registration & Onboarding BLOGR - Backend - Feature: User & Identity Management Use Case - User Registration & Onboarding ValidationEmailAlreadyRegistered orUsernameAlreadyTaken enforcedReturn error responseyesEmail or Username already exists?noAccount CreationUser entity createdCreate new User entityPersist user to databasePost-RegistrationSend welcome emailConfiguration-driven flowAccess token generation enabled?yesnoGenerate JWT access tokenReturn token and user detailsReturn success message   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.
Use Case - User Registration & Onboarding BLOGR - Backend - Feature: User & Identity Management Use Case - User Registration & Onboarding ValidationEmailAlreadyRegistered orUsernameAlreadyTaken enforcedReturn error responseyesEmail or Username already exists?noAccount CreationUser entity createdCreate new User entityPersist user to databasePost-RegistrationSend welcome emailConfiguration-driven flowAccess token generation enabled?yesnoGenerate JWT access tokenReturn token and user detailsReturn success message   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.

Secure Authentication

Use Case - Secure Authentication BLOGR - Backend - Feature: User & Identity Management Use Case - Secure Authentication AuthenticationReceive user credentials (email/password)Authenticate user against database recordsInvalidCredentials enforcedReturn 'Unauthorized' errornoCredentials are valid?yesAuthorizationInactiveUserAccount enforcedReturn 'Forbidden' errornoUser account is active?yesToken IssuanceAccessTokenValidityPeriod checkedACCESS_TOKEN_EXPIRE_MINUTES > 0?yesnoCreate JWT access token with expirationReturn token and user detailsLog configuration errorReturn server error   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.
Use Case - Secure Authentication BLOGR - Backend - Feature: User & Identity Management Use Case - Secure Authentication AuthenticationReceive user credentials (email/password)Authenticate user against database recordsInvalidCredentials enforcedReturn 'Unauthorized' errornoCredentials are valid?yesAuthorizationInactiveUserAccount enforcedReturn 'Forbidden' errornoUser account is active?yesToken IssuanceAccessTokenValidityPeriod checkedACCESS_TOKEN_EXPIRE_MINUTES > 0?yesnoCreate JWT access token with expirationReturn token and user detailsLog configuration errorReturn server error   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.

Password Management

Use Case - Password Management BLOGR - Backend - Feature: User & Identity Management Use Case - Password Management Forgot PasswordReceive email for password resetPasswordResetTokenExpiration enforcedGenerate secure, time-limited reset tokenSend reset token via emailReturn success confirmationReset PasswordReceive reset token and new passwordInvalidOrExpiredPasswordResetToken checkedToken is valid and not expired?yesnoHash the new passwordUpdate user password in databaseReturn success messageReturn 'Invalid Token' error   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.
Use Case - Password Management BLOGR - Backend - Feature: User & Identity Management Use Case - Password Management Forgot PasswordReceive email for password resetPasswordResetTokenExpiration enforcedGenerate secure, time-limited reset tokenSend reset token via emailReturn success confirmationReset PasswordReceive reset token and new passwordInvalidOrExpiredPasswordResetToken checkedToken is valid and not expired?yesnoHash the new passwordUpdate user password in databaseReturn success messageReturn 'Invalid Token' error   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.

Architecture

Architecture BLOGR - Backend - Feature: User & Identity Management Architecture API Gateway LayerUtility LayerExternal Systems & Servicesauth.pysecurity.pyDatabaseEmail Serviceuses for hashing & tokenspersists & retrieves user datasends notifications   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.
Architecture BLOGR - Backend - Feature: User & Identity Management Architecture API Gateway LayerUtility LayerExternal Systems & Servicesauth.pysecurity.pyDatabaseEmail Serviceuses for hashing & tokenspersists & retrieves user datasends notifications   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.

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

Call Flow BLOGR - Backend - Feature: User & Identity Management Call Flow /change-password/forgot-password/reset-password/signin/signupget_tokenUserService.get_user_by_idUserService.update_passwordlogger.errorlogger.infoverify_passwordUserService.get_user_by_emailcreate_password_reset_tokenemail_service.send_password_reset_emaillogger.warningverify_password_reset_tokenUserResponse.from_ormUserService.authenticate_usercreate_access_tokenUserService.create_userUserService.get_user_by_usernameemail_service.send_welcome_emailverify_token   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.
Call Flow BLOGR - Backend - Feature: User & Identity Management Call Flow /change-password/forgot-password/reset-password/signin/signupget_tokenUserService.get_user_by_idUserService.update_passwordlogger.errorlogger.infoverify_passwordUserService.get_user_by_emailcreate_password_reset_tokenemail_service.send_password_reset_emaillogger.warningverify_password_reset_tokenUserResponse.from_ormUserService.authenticate_usercreate_access_tokenUserService.create_userUserService.get_user_by_usernameemail_service.send_welcome_emailverify_token   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.

Business Rules

Business Rules BLOGR - Backend - Feature: User & Identity Management Business Rules User & Identity Management RulesUserEmailAlreadyRegisteredUsernameAlreadyTakenInvalidCredentialsInactiveUserAccountIncorrectCurrentPasswordPasswordResetTokenInvalidOrExpiredPasswordResetTokenPasswordResetTokenExpirationPasswordResetTokenTypeValidationAccessTokenAccessTokenExpirationAccessTokenValidityPeriodGeneralInvalidCredentialsRejection   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.
Business Rules BLOGR - Backend - Feature: User & Identity Management Business Rules User & Identity Management RulesUserEmailAlreadyRegisteredUsernameAlreadyTakenInvalidCredentialsInactiveUserAccountIncorrectCurrentPasswordPasswordResetTokenInvalidOrExpiredPasswordResetTokenPasswordResetTokenExpirationPasswordResetTokenTypeValidationAccessTokenAccessTokenExpirationAccessTokenValidityPeriodGeneralInvalidCredentialsRejection   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.
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. User
Credentials
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. User
Password
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. AccessToken
User
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

Domain Model BLOGR - Backend - Feature: User & Identity Management Domain Model Identity & Access Management Context«aggregate_root»Userusername: stringemail: stringhashed_password: stringis_active: booleanupdatePassword()authenticate()«value_object»AccessTokentoken_string: stringexpires_at: datetime«value_object»PasswordResetTokentoken_string: stringexpires_at: datetimetype: string«value_object»Credentialsidentifier: stringpassword: stringissues1*generates for11is authenticated by1   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.
Domain Model BLOGR - Backend - Feature: User & Identity Management Domain Model Identity & Access Management Context«aggregate_root»Userusername: stringemail: stringhashed_password: stringis_active: booleanupdatePassword()authenticate()«value_object»AccessTokentoken_string: stringexpires_at: datetime«value_object»PasswordResetTokentoken_string: stringexpires_at: datetimetype: string«value_object»Credentialsidentifier: stringpassword: stringissues1*generates for11is authenticated by1   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.
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

KeyImpact
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.