Skip to content

security.py

This file centralizes core security functionalities, including password hashing, JWT-based access token creation and verification, and secure password reset token management. It ensures robust authentication and authorization mechanisms for the application.

Scope

  • Manages password hashing and secure verification processes.

  • Generates and encodes secure JSON Web Tokens for user authentication.

  • Validates incoming access tokens, ensuring their integrity and expiration.

  • Creates and verifies specialized tokens for password reset workflows.

  • Handles authentication failures by raising appropriate HTTP exceptions.

File diagram - "security.py" /app/core/security.pyFile diagram - "security.py"  GlobalImportsdatetimetimedeltaJWTErrorjwtCryptContextDependsHTTPExceptionstatusHTTPBearerHTTPAuthCredentialssettings/app/core/security.pypwd_contextsecurityhash_password()verify_password()create_access_token()verify_token()create_password_reset_token()verify_password_reset_token()async get_token()CryptContext()HTTPBearer()hash_passwordpwd_context.hash()verify_passwordpwd_context.verify()create_access_tokento_encodeexpireencoded_jwtdata.copy()datetime.utcnow()timedelta()to_encode.update()jwt.encode()verify_tokenpayloadjwt.decode()create_password_reset_tokento_encodeexpireencoded_jwtdata.copy()datetime.utcnow()timedelta()to_encode.update()jwt.encode()verify_password_reset_tokenpayloadjwt.decode()payload.get()get_tokentokenpayloadDepends()HTTPException()verify_token()   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.
File diagram - "security.py" /app/core/security.pyFile diagram - "security.py"  GlobalImportsdatetimetimedeltaJWTErrorjwtCryptContextDependsHTTPExceptionstatusHTTPBearerHTTPAuthCredentialssettings/app/core/security.pypwd_contextsecurityhash_password()verify_password()create_access_token()verify_token()create_password_reset_token()verify_password_reset_token()async get_token()CryptContext()HTTPBearer()hash_passwordpwd_context.hash()verify_passwordpwd_context.verify()create_access_tokento_encodeexpireencoded_jwtdata.copy()datetime.utcnow()timedelta()to_encode.update()jwt.encode()verify_tokenpayloadjwt.decode()create_password_reset_tokento_encodeexpireencoded_jwtdata.copy()datetime.utcnow()timedelta()to_encode.update()jwt.encode()verify_password_reset_tokenpayloadjwt.decode()payload.get()get_tokentokenpayloadDepends()HTTPException()verify_token()   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.

Imports

  • datetime from datetime

    Provides date and time objects for token expiration calculations. This ensures tokens have a defined lifespan, enhancing security by limiting exposure.

  • JWTError, jwt from jose

    Facilitates JSON Web Token (JWT) creation, encoding, and decoding. It handles cryptographic operations essential for secure token-based authentication within the application.

  • CryptContext from passlib.context

    Manages password hashing and verification using secure algorithms like bcrypt. This ensures sensitive user passwords are never stored in plain text, protecting user data.

  • Depends, HTTPException, status from fastapi

    Provides core FastAPI utilities for dependency injection, error handling, and HTTP status codes. These are crucial for integrating security functions into API routes.

  • HTTPBearer, HTTPAuthCredentials from fastapi.security

    Offers FastAPI-specific security utilities for HTTP Bearer token authentication. It simplifies extracting and validating tokens from incoming request headers.

  • settings from app.core.config

    Imports application-wide configuration settings, such as SECRET_KEY and ACCESS_TOKEN_EXPIRE_MINUTES. This centralizes sensitive parameters, promoting secure and flexible deployment.

Variables

  • pwd_context

    An instance of CryptContext configured for password hashing. It provides a secure and consistent interface for handling password storage and verification across the application.

  • security

    An instance of HTTPBearer used by FastAPI for extracting Bearer tokens. It defines the authentication scheme, enabling token-based security for protected API endpoints.

Global Code

Initializes the password hashing context using bcrypt scheme. This setup ensures all password operations leverage strong, modern cryptographic practices for user data protection. Instantiates the HTTP Bearer token scheme for FastAPI. This object is used as a dependency to automatically extract and provide authentication credentials from request headers.

Functions

verify_password

public

Verifies a plain-text password against its hashed counterpart using a secure password hashing context. This function ensures user-provided passwords match stored hashes without exposing the original password, crucial for authentication processes.
=== " "

Activity Diagram - "verify_password" /app/core/security.pyActivity Diagram - "verify_password"  Inputs: plain_password, hashed_passwordVerify plain password against hashed password usingpwd_contextreturn Boolean result of verification   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.
Activity Diagram - "verify_password" /app/core/security.pyActivity Diagram - "verify_password"  Inputs: plain_password, hashed_passwordVerify plain password against hashed password usingpwd_contextreturn Boolean result of verification   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.

Method diagram - "verify_password" /app/core/security.pyMethod diagram - "verify_password"  verify_passwordpwd_context.verify()   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.
Method diagram - "verify_password" /app/core/security.pyMethod diagram - "verify_password"  verify_passwordpwd_context.verify()   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.

Sequence Diagram - "verify_password" Sequence Diagram - "verify_password"  verify_passwordpwd_contextCallerverify_passwordpwd_contextCallerCallerverify_passwordverify_passwordpwd_contextpwd_contextverify_passwordpwd_contextFunction Callverify_password(plain_password, hashed_password)verify(plain_password, hashed_password)boolean_resultboolean_result/app/core/security.py   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.
Sequence Diagram - "verify_password" Sequence Diagram - "verify_password"  verify_passwordpwd_contextCallerverify_passwordpwd_contextCallerCallerverify_passwordverify_passwordpwd_contextpwd_contextverify_passwordpwd_contextFunction Callverify_password(plain_password, hashed_password)verify(plain_password, hashed_password)boolean_resultboolean_result/app/core/security.py   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.

Syntax

def verify_password(plain_password: str, hashed_password: str) -> bool:

Input Parameters

  • plain_password (str)

    The unhashed, plain-text password string provided by the user for verification. This input is compared against the stored hashed password to confirm authenticity during login or password change operations.

  • hashed_password (str)

    The securely hashed password string retrieved from storage, typically a database. This value is the reference against which the plain_password is checked, ensuring secure comparison without direct exposure.

Output / Return Values

  • verification_result (bool)

    A boolean indicating whether the plain_password successfully matches the hashed_password. Returns True if they match, False otherwise. This result determines authentication success or failure for users.

Logic / Execution Flow

  • Call the verify() method of the global pwd_context object, passing plain_password and hashed_password as arguments.
  • Return the boolean result obtained from the pwd_context.verify() method, indicating password match status.

Usage Tips

  • Always use this function to compare user-provided passwords with stored hashes. Never store plain-text passwords directly, and always hash new passwords using pwd_context.hash() before storage for security.

Additional Notes

  • pwd_context is typically configured globally with a strong hashing algorithm like bcrypt. Ensure this context is properly initialized and accessible for secure password operations throughout the application lifecycle.

hash_password

public

This function securely hashes a plain-text password using a pre-configured password context. It ensures sensitive user credentials are never stored in plain text, providing essential security for authentication systems. This is crucial for protecting user data.
=== " "

Activity Diagram - "hash_password" /app/core/security.pyActivity Diagram - "hash_password"  Inputs: passwordHash password using pwd_contextreturn Hashed password string   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.
Activity Diagram - "hash_password" /app/core/security.pyActivity Diagram - "hash_password"  Inputs: passwordHash password using pwd_contextreturn Hashed password string   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.

Method diagram - "hash_password" /app/core/security.pyMethod diagram - "hash_password"  hash_passwordpwd_context.hash()   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.
Method diagram - "hash_password" /app/core/security.pyMethod diagram - "hash_password"  hash_passwordpwd_context.hash()   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.

Sequence Diagram - "hash_password" Sequence Diagram - "hash_password"  hash_passwordpwd_contextCallerhash_passwordpwd_contextCallerCallerhash_passwordhash_passwordpwd_contextpwd_contexthash_passwordpwd_contextFunction Callhash_password(password)hash(password)hashed_passwordFunction Returnhashed_password/app/core/security.py   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.
Sequence Diagram - "hash_password" Sequence Diagram - "hash_password"  hash_passwordpwd_contextCallerhash_passwordpwd_contextCallerCallerhash_passwordhash_passwordpwd_contextpwd_contexthash_passwordpwd_contextFunction Callhash_password(password)hash(password)hashed_passwordFunction Returnhashed_password/app/core/security.py   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.

Syntax

def hash_password(password: str) -> str:

Input Parameters

  • password (str)

    The plain-text password string to be securely hashed before storage or comparison. This input is critical for user authentication processes, ensuring that sensitive credentials are never exposed directly within the system. It must be a valid string.

Output / Return Values

  • hashed_password (str)

    The securely hashed password string generated by the pwd_context. This output is suitable for storage in a database and subsequent comparison during user login attempts, ensuring robust security without storing original passwords.

Logic / Execution Flow

  • Call pwd_context.hash() method with the provided password to generate a hashed version.
  • Return the securely hashed password string.

Usage Tips

  • Always hash passwords before storing them in any persistent storage, even temporary caches. This prevents exposure of sensitive user data if the database is compromised, maintaining strong security practices.

  • Ensure pwd_context is properly configured with a strong hashing algorithm and appropriate work factors. Regularly review and update hashing parameters to adapt to evolving security standards and computational power.

Additional Notes

  • The pwd_context object, typically a global instance of CryptContext, manages the hashing algorithm and salt generation. Its configuration dictates the strength and computational cost of the resulting password hash.

  • This function is a fundamental building block for secure user authentication. It should be used consistently across all password-handling operations, including registration, password changes, and verification processes, for system integrity.

create_password_reset_token

public

This function generates a secure JSON Web Token for password reset operations. It encodes user data with an expiration time and a specific type, ensuring token validity. This token is crucial for securely initiating and completing user password recovery processes.
=== " "

Activity Diagram - "create_password_reset_token" /app/core/security.pyActivity Diagram - "create_password_reset_token"  Inputs: dataCreate a copy of input dataCalculate expiration time (24 hours from now)Update data with expiration and type "password_reset"Encode data into JWT using secret key and algorithmreturn Encoded JWT string   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.
Activity Diagram - "create_password_reset_token" /app/core/security.pyActivity Diagram - "create_password_reset_token"  Inputs: dataCreate a copy of input dataCalculate expiration time (24 hours from now)Update data with expiration and type "password_reset"Encode data into JWT using secret key and algorithmreturn Encoded JWT string   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.

Method diagram - "create_password_reset_token" /app/core/security.pyMethod diagram - "create_password_reset_token"  create_password_reset_tokento_encodeexpireencoded_jwtdata.copy()datetime.utcnow()timedelta()to_encode.update()jwt.encode()   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.
Method diagram - "create_password_reset_token" /app/core/security.pyMethod diagram - "create_password_reset_token"  create_password_reset_tokento_encodeexpireencoded_jwtdata.copy()datetime.utcnow()timedelta()to_encode.update()jwt.encode()   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.

Sequence Diagram - "create_password_reset_token" Sequence Diagram - "create_password_reset_token"  create_password_reset_tokenjwtCallercreate_password_reset_tokenjwtCallerCallercreate_password_reset_tokencreate_password_reset_tokenjwtjwtcreate_password_reset_tokenjwtFunction Callcreate_password_reset_token(data)Internal ProcessingCreate copy of input data (to_encode = data.copy())Calculate expiration time (expire = datetime.utcnow() +timedelta(hours=24))Add expiration and type to token data(to_encode.update({"exp": expire, "type":"password_reset"}))JWT Encodingencode(to_encode, settings.SECRET_KEY,settings.ALGORITHM)encoded_jwtFunction Returnencoded_jwt/app/core/security.py   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.
Sequence Diagram - "create_password_reset_token" Sequence Diagram - "create_password_reset_token"  create_password_reset_tokenjwtCallercreate_password_reset_tokenjwtCallerCallercreate_password_reset_tokencreate_password_reset_tokenjwtjwtcreate_password_reset_tokenjwtFunction Callcreate_password_reset_token(data)Internal ProcessingCreate copy of input data (to_encode = data.copy())Calculate expiration time (expire = datetime.utcnow() +timedelta(hours=24))Add expiration and type to token data(to_encode.update({"exp": expire, "type":"password_reset"}))JWT Encodingencode(to_encode, settings.SECRET_KEY,settings.ALGORITHM)encoded_jwtFunction Returnencoded_jwt/app/core/security.py   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.

Syntax

def create_password_reset_token(data: dict) -> str:

Input Parameters

  • data (dict)

    This dictionary contains user-specific information required for the password reset token. It typically includes the user's identifier, ensuring the token is linked to the correct account. This data is securely encoded within the JWT payload for later verification.

Output / Return Values

  • encoded_jwt (str)

    The function returns a string representing the securely encoded JWT. This token contains the user's data, expiration, and type, which is essential for verifying password reset requests. It serves as a temporary, verifiable credential.

Logic / Execution Flow

  • Create a mutable copy of the input data dictionary, storing it in to_encode.
  • Calculate the expiration time by adding 24 hours to the current UTC time using datetime.utcnow() and timedelta(hours=24), storing it in expire.
  • Update the to_encode dictionary by adding two new key-value pairs: "exp" set to the calculated expire time, and "type" set to the string "password_reset".
  • Encode the to_encode dictionary into a JSON Web Token using jwt.encode(), providing the settings.SECRET_KEY and settings.ALGORITHM for cryptographic signing.
  • Return the generated encoded_jwt string.

Usage Tips

  • Ensure the data dictionary passed contains sufficient, non-sensitive information to identify the user for reset. Avoid including highly confidential data directly within the token payload.

  • Always store the settings.SECRET_KEY securely and rotate it periodically to maintain the integrity of generated tokens. Compromised keys invalidate all existing tokens.

Additional Notes

  • The token's 24-hour expiration (timedelta(hours=24)) provides a reasonable window for users to complete the reset process. Adjust this duration based on security policies.

  • The type field ("password_reset") within the token payload is vital for distinguishing this token from other JWTs, preventing misuse in different authentication contexts.

create_access_token

public

This function generates a JSON Web Token (JWT) for authentication purposes, encoding provided data. It calculates an expiration time for the token, either custom or default. This token is crucial for securing API endpoints and user sessions.
=== " "

Activity Diagram - "create_access_token" /app/core/security.pyActivity Diagram - "create_access_token"  Inputs: data, expires_deltaCreate copy of input dataexpires_delta is provided?yesnoCalculate expiration time using expires_deltaCalculate expiration time using default minutes from settingsAdd expiration time to data for encodingEncode data into JWT using secret key and algorithmreturn Encoded JWT string   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.
Activity Diagram - "create_access_token" /app/core/security.pyActivity Diagram - "create_access_token"  Inputs: data, expires_deltaCreate copy of input dataexpires_delta is provided?yesnoCalculate expiration time using expires_deltaCalculate expiration time using default minutes from settingsAdd expiration time to data for encodingEncode data into JWT using secret key and algorithmreturn Encoded JWT string   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.

Method diagram - "create_access_token" /app/core/security.pyMethod diagram - "create_access_token"  create_access_tokento_encodeexpireencoded_jwtdata.copy()datetime.utcnow()timedelta()to_encode.update()jwt.encode()   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.
Method diagram - "create_access_token" /app/core/security.pyMethod diagram - "create_access_token"  create_access_tokento_encodeexpireencoded_jwtdata.copy()datetime.utcnow()timedelta()to_encode.update()jwt.encode()   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.

Sequence Diagram - "create_access_token" Sequence Diagram - "create_access_token"  create_access_tokenCallercreate_access_tokendatetimetimedeltasettingsjwtCallerCallercreate_access_tokencreate_access_tokendatetimedatetimetimedeltatimedeltasettingssettingsjwtjwtcreate_access_tokenFunction Callcreate_access_token(data, expires_delta)Prepare Token Datato_encode = data.copy()Creates a mutable copy of the input dataDetermine Expiration Timealt[expires_delta is provided]utcnow()current_utc_timeexpire = current_utc_time + expires_delta[expires_delta is None]utcnow()current_utc_timeACCESS_TOKEN_EXPIRE_MINUTESminutes_valuetimedelta(minutes=minutes_value)time_delta_objectexpire = current_utc_time + time_delta_objectto_encode.update({"exp": expire})Adds expiration timestamp to token dataEncode JWTSECRET_KEYsecret_key_valueALGORITHMalgorithm_valueencode(to_encode, secret_key_value, algorithm_value)encoded_jwtFunction Returnencoded_jwt/app/core/security.py   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.
Sequence Diagram - "create_access_token" Sequence Diagram - "create_access_token"  create_access_tokenCallercreate_access_tokendatetimetimedeltasettingsjwtCallerCallercreate_access_tokencreate_access_tokendatetimedatetimetimedeltatimedeltasettingssettingsjwtjwtcreate_access_tokenFunction Callcreate_access_token(data, expires_delta)Prepare Token Datato_encode = data.copy()Creates a mutable copy of the input dataDetermine Expiration Timealt[expires_delta is provided]utcnow()current_utc_timeexpire = current_utc_time + expires_delta[expires_delta is None]utcnow()current_utc_timeACCESS_TOKEN_EXPIRE_MINUTESminutes_valuetimedelta(minutes=minutes_value)time_delta_objectexpire = current_utc_time + time_delta_objectto_encode.update({"exp": expire})Adds expiration timestamp to token dataEncode JWTSECRET_KEYsecret_key_valueALGORITHMalgorithm_valueencode(to_encode, secret_key_value, algorithm_value)encoded_jwtFunction Returnencoded_jwt/app/core/security.py   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.

Syntax

def create_access_token(data: dict, expires_delta: timedelta = None) -> str:

Input Parameters

  • data (dict)

    A dictionary containing the payload data to be encoded into the JWT. This typically includes user identification or session-specific information. Ensure sensitive data is not directly stored here.

  • expires_delta (timedelta)

    An optional timedelta object specifying the token's lifespan. If provided, it overrides the default expiration setting. This allows for flexible token validity periods based on specific use cases.

Output / Return Values

  • encoded_jwt (str)

    A string representing the securely encoded JWT. This token is then typically sent to the client for subsequent authenticated requests. It contains the payload and expiration information.

Logic / Execution Flow

  • Create a mutable copy of the input data dictionary, named to_encode, to avoid modifying the original dictionary directly.
  • Check if an expires_delta timedelta object was provided as an argument to the function.
    • If expires_delta is provided:
      • Calculate the expire timestamp by adding expires_delta to the current UTC time using datetime.utcnow().
    • If expires_delta is not provided (i.e., None):
      • Calculate the expire timestamp by adding a default timedelta of settings.ACCESS_TOKEN_EXPIRE_MINUTES to the current UTC time.
  • Update the to_encode dictionary by adding an exp key with the calculated expire timestamp, representing the token's expiration.
  • Encode the to_encode dictionary into a JWT string using jwt.encode(), applying settings.SECRET_KEY and settings.ALGORITHM.
  • Return the resulting encoded_jwt string, which is ready for client consumption.

Usage Tips

  • Always use a strong, securely managed settings.SECRET_KEY for JWT signing to prevent token tampering and unauthorized access. Rotate this key periodically for enhanced security.

  • Carefully manage expires_delta to balance security and user experience. Shorter lifespans enhance security but require more frequent re-authentication, impacting user flow.

Additional Notes

  • The datetime.utcnow() function is used for expiration calculation, ensuring time zone independence. This is critical for consistent token validation across different server environments and client locations.

  • This function relies on global settings for SECRET_KEY, ALGORITHM, and ACCESS_TOKEN_EXPIRE_MINUTES. Ensure these are properly configured and loaded before calling this token creation utility.

verify_token

public

This function verifies a JSON Web Token (JWT) by decoding it using a secret key and algorithm. It extracts the payload if valid, providing user identity or session data. Essential for securing API endpoints and authenticating requests across the application.
=== " "

Activity Diagram - "verify_token" /app/core/security.pyActivity Diagram - "verify_token"  Inputs: tokenTry Block: Attempt JWT DecodingAttempt to decode JWT token using secret key and algorithmJWTError is raisedAssign decoded payloadreturn payloadyesJWT decoding succeeds?noCatch Block: Handle JWTErrorThis block executes if JWTError was raisedHandle JWTErrorreturn NoneFinally Block: Cleanup (if any)This block is conceptually executed before returns, but diagrammatically unreachable due to early returns intry/catch.No explicit cleanup operations   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.
Activity Diagram - "verify_token" /app/core/security.pyActivity Diagram - "verify_token"  Inputs: tokenTry Block: Attempt JWT DecodingAttempt to decode JWT token using secret key and algorithmJWTError is raisedAssign decoded payloadreturn payloadyesJWT decoding succeeds?noCatch Block: Handle JWTErrorThis block executes if JWTError was raisedHandle JWTErrorreturn NoneFinally Block: Cleanup (if any)This block is conceptually executed before returns, but diagrammatically unreachable due to early returns intry/catch.No explicit cleanup operations   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.

Method diagram - "verify_token" /app/core/security.pyMethod diagram - "verify_token"  verify_tokenpayloadjwt.decode()   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.
Method diagram - "verify_token" /app/core/security.pyMethod diagram - "verify_token"  verify_tokenpayloadjwt.decode()   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.

Sequence Diagram - "verify_token" Sequence Diagram - "verify_token"  verify_tokenjwtCallerverify_tokenjwtCallerCallerverify_tokenverify_tokenjwtjwtverify_tokenjwtFunction Callverify_token(token)alt[Try Block: Successful Token Decoding]decode(token, settings.SECRET_KEY,algorithms=[settings.ALGORITHM])payloadpayload[Catch Block: JWTError Occurs]JWTError is caughtNone/app/core/security.py   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.
Sequence Diagram - "verify_token" Sequence Diagram - "verify_token"  verify_tokenjwtCallerverify_tokenjwtCallerCallerverify_tokenverify_tokenjwtjwtverify_tokenjwtFunction Callverify_token(token)alt[Try Block: Successful Token Decoding]decode(token, settings.SECRET_KEY,algorithms=[settings.ALGORITHM])payloadpayload[Catch Block: JWTError Occurs]JWTError is caughtNone/app/core/security.py   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.

Syntax

def verify_token(token: str) -> dict:

Input Parameters

  • token (str)

    The token parameter is a string representing the JSON Web Token to be verified. This token typically contains encoded user information or session data, crucial for authenticating requests and authorizing access to protected resources.

Output / Return Values

  • payload (dict)

    The payload represents the decoded contents of the JWT as a dictionary if verification succeeds. It contains claims like user ID or roles. If token verification fails due to JWTError, None is returned, indicating an invalid or expired token.

Logic / Execution Flow

  • Attempt to decode the provided token using jwt.decode():
    • The decoding process uses settings.SECRET_KEY for signature verification.
    • The decoding process uses settings.ALGORITHM to specify the expected algorithm.
  • If decoding is successful, return the payload dictionary containing the token's claims.
  • If a JWTError occurs during decoding (e.g., invalid signature, expired token):
    • Catch the JWTError exception.
    • Return None, indicating that the token could not be verified.

Usage Tips

  • Integrate verify_token() early in your request processing pipeline to ensure all protected routes are secured. Always check for a None return value, indicating an invalid token, and respond with an appropriate authentication error.

  • Ensure settings.SECRET_KEY and settings.ALGORITHM are securely managed and consistent across token generation and verification. Mismatched keys or algorithms will cause JWTError, leading to failed authentication attempts.

Additional Notes

  • This function only verifies the token's integrity and expiration, not its revocation status. For robust security, implement a token revocation mechanism (e.g., a blacklist) to invalidate tokens before their natural expiration.

  • The jwt.decode() function automatically handles common JWT validation checks like expiration (exp) and not-before (nbf) claims. Ensure these claims are properly set during token creation for effective security.

get_token

public

This asynchronous function retrieves and validates an authentication token from HTTP credentials. It ensures the provided token is valid and returns the decoded payload. Essential for securing API endpoints, it integrates with FastAPI's dependency injection system for seamless authentication flow.
=== " "

Activity Diagram - "get_token" /app/core/security.pyActivity Diagram - "get_token"  Inputs: credentialsExtract token from credentialsVerify token and get payloadpayload is valid?yesnoreturn payloadRaise HTTPException (401 Unauthorized)   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.
Activity Diagram - "get_token" /app/core/security.pyActivity Diagram - "get_token"  Inputs: credentialsExtract token from credentialsVerify token and get payloadpayload is valid?yesnoreturn payloadRaise HTTPException (401 Unauthorized)   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.

Method diagram - "get_token" /app/core/security.pyMethod diagram - "get_token"  get_tokentokenpayloadDepends()HTTPException()verify_token()verify_tokenpayloadjwt.decode()   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.
Method diagram - "get_token" /app/core/security.pyMethod diagram - "get_token"  get_tokentokenpayloadDepends()HTTPException()verify_token()verify_tokenpayloadjwt.decode()   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.

Sequence Diagram - "get_token" Sequence Diagram - "get_token"  get_tokensecurityverify_tokenCallerget_tokensecurityverify_tokenCallerCallerget_tokenget_tokensecuritysecurityverify_tokenverify_tokenget_tokensecurityverify_tokenFunction Entryget_token(credentials: Depends(security))FastAPI injects credentials via Depends(security)Dependency Resolutioncall()credentialsToken Extractiontoken = credentials.credentialsToken Verificationverify_token(token)payloadRaise HTTPException(401, "Invalid authenticationcredentials")Payload Validationalt[not payload (token invalid)]HTTPException(401)[payload (token valid)]payload/app/core/security.py   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.
Sequence Diagram - "get_token" Sequence Diagram - "get_token"  get_tokensecurityverify_tokenCallerget_tokensecurityverify_tokenCallerCallerget_tokenget_tokensecuritysecurityverify_tokenverify_tokenget_tokensecurityverify_tokenFunction Entryget_token(credentials: Depends(security))FastAPI injects credentials via Depends(security)Dependency Resolutioncall()credentialsToken Extractiontoken = credentials.credentialsToken Verificationverify_token(token)payloadRaise HTTPException(401, "Invalid authenticationcredentials")Payload Validationalt[not payload (token invalid)]HTTPException(401)[payload (token valid)]payload/app/core/security.py   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.

Syntax

async def get_token(credentials: HTTPAuthCredentials = Depends(security)) -> dict:

Input Parameters

  • credentials (HTTPAuthCredentials)

    Represents the HTTP authentication credentials, typically a Bearer token. This parameter is automatically injected by FastAPI's Depends(security) mechanism, providing the raw token string for validation.

Output / Return Values

  • payload (dict)

    The decoded JWT payload as a dictionary, containing user-specific information like user ID or roles. This payload represents the authenticated user's identity and permissions for subsequent operations.

Exceptions

  • HTTPException 401 Unauthorized [401]

    Raised when the token extracted from credentials is invalid or cannot be verified. This indicates that the authentication credentials provided by the client are either missing, malformed, or expired.

Logic / Execution Flow

  • Extract the token string from the credentials.credentials object.
  • Call the verify_token() function, passing the extracted token, to decode and validate it.
  • Check if the returned payload from verify_token() is None:
    • If payload is None, indicating invalid credentials:
      • Raise an HTTPException with status.HTTP_401_UNAUTHORIZED and a detail message "Invalid authentication credentials".
  • If payload is not None, return the decoded payload dictionary.

Usage Tips

  • Always ensure the security dependency is correctly configured to extract tokens from request headers. This function relies on HTTPAuthCredentials being properly populated before execution.

  • Integrate this get_token function as a FastAPI dependency for protected routes. This automatically handles token extraction and validation, simplifying secure endpoint development significantly.

Additional Notes

  • The verify_token function (assumed to be defined elsewhere) is crucial for JWT decoding and signature verification. Its implementation directly impacts the security and robustness of this authentication flow.

  • This function only validates the token's integrity and expiration. Further authorization checks (e.g., role-based access control) should be performed on the returned payload in subsequent dependency functions.

verify_password_reset_token

public

This function verifies a given `token` as a password reset token using `JWT` decoding. It ensures the token type is `password_reset` and returns the decoded `payload` or `None` if invalid. Essential for securing password reset workflows.
=== " "

Activity Diagram - "verify_password_reset_token" /app/core/security.pyActivity Diagram - "verify_password_reset_token"  Inputs: tokenTry Block: Decode JWT TokenAttempt to decode JWT tokenJWTError occurs during decode?yesnoSet jwt_error_occurred = trueExtract payload from tokenSet jwt_error_occurred = falseCatch Block: Handle JWTErrorNo JWTError, proceed with payload checkLog JWT decoding errorreturn Noneyesjwt_error_occurred is true?noFinally Block: CleanupNo explicit cleanup operations in codeExecution continues here if no JWTError occurredContinuepayload.get("type") is 'password_reset'?yesnoreturn Decoded payloadreturn None   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.
Activity Diagram - "verify_password_reset_token" /app/core/security.pyActivity Diagram - "verify_password_reset_token"  Inputs: tokenTry Block: Decode JWT TokenAttempt to decode JWT tokenJWTError occurs during decode?yesnoSet jwt_error_occurred = trueExtract payload from tokenSet jwt_error_occurred = falseCatch Block: Handle JWTErrorNo JWTError, proceed with payload checkLog JWT decoding errorreturn Noneyesjwt_error_occurred is true?noFinally Block: CleanupNo explicit cleanup operations in codeExecution continues here if no JWTError occurredContinuepayload.get("type") is 'password_reset'?yesnoreturn Decoded payloadreturn None   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.

Method diagram - "verify_password_reset_token" /app/core/security.pyMethod diagram - "verify_password_reset_token"  verify_password_reset_tokenpayloadjwt.decode()payload.get()   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.
Method diagram - "verify_password_reset_token" /app/core/security.pyMethod diagram - "verify_password_reset_token"  verify_password_reset_tokenpayloadjwt.decode()payload.get()   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.

Sequence Diagram - "verify_password_reset_token" Sequence Diagram - "verify_password_reset_token"  verify_password_reset_tokenjwtsettingssettingsCallerverify_password_reset_tokenjwtsettingsCallerCallerverify_password_reset_tokenverify_password_reset_tokenjwtjwtsettingssettingsverify_password_reset_tokenjwtsettingssettingsFunction Callverify_password_reset_token(token)Try Block: Decode JWTRetrieve JWT configuration valuesGet SECRET_KEYSECRET_KEYGet ALGORITHMALGORITHMdecode(token, SECRET_KEY, algorithms=[ALGORITHM])payloadalt[payload.get("type") == "password_reset"]payload[payload.get("type") != "password_reset"]Nonebreak[JWTError: Token decoding failed]None/app/core/security.py   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.
Sequence Diagram - "verify_password_reset_token" Sequence Diagram - "verify_password_reset_token"  verify_password_reset_tokenjwtsettingssettingsCallerverify_password_reset_tokenjwtsettingsCallerCallerverify_password_reset_tokenverify_password_reset_tokenjwtjwtsettingssettingsverify_password_reset_tokenjwtsettingssettingsFunction Callverify_password_reset_token(token)Try Block: Decode JWTRetrieve JWT configuration valuesGet SECRET_KEYSECRET_KEYGet ALGORITHMALGORITHMdecode(token, SECRET_KEY, algorithms=[ALGORITHM])payloadalt[payload.get("type") == "password_reset"]payload[payload.get("type") != "password_reset"]Nonebreak[JWTError: Token decoding failed]None/app/core/security.py   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.

Syntax

def verify_password_reset_token(token: str) -> dict:

Input Parameters

  • token (str)

    This token string represents the JWT issued for a password reset operation. It contains encoded user information and expiration data. Crucial for authenticating reset requests.

Output / Return Values

  • payload (dict | None)

    Returns the decoded JWT payload as a dictionary if valid and of type password_reset. Otherwise, it returns None, indicating an invalid or expired token.

Exceptions

  • JWTError

    Raised by jwt.decode() if the token is invalid, expired, or tampered with. This exception is caught, leading to a None return, preventing sensitive information exposure.

Logic / Execution Flow

  • Attempt to decode the provided token using jwt.decode():
    • Use settings.SECRET_KEY for signature verification.
    • Specify settings.ALGORITHM for decoding.
  • If JWTError occurs during decoding:
    • Return None, indicating an invalid or expired token.
  • If decoding is successful, check the payload's type field:
    • If payload.get("type") is not equal to "password_reset":
      • Return None, as the token is not intended for password reset.
  • If the payload is valid and of type password_reset:
    • Return the decoded payload dictionary.

Usage Tips

  • Always ensure the token is securely transmitted (e.g., via HTTPS) to prevent interception and replay attacks. Validate token expiration and user identity after successful decoding.

  • Integrate this function early in your password reset endpoint to quickly reject invalid or malformed tokens. This reduces unnecessary database lookups and improves security.

Additional Notes

  • The settings.SECRET_KEY and settings.ALGORITHM are critical for JWT security. Ensure they are robustly managed and never exposed in client-side code or version control.

  • Returning None for both JWTError and incorrect type prevents attackers from distinguishing between an invalid token and a valid token of the wrong type.

FAQs

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

Insights

Metric Score Level
Complexity 0.70 High Complexity
Security 0.80 Secure
Performance 0.80 Optimised