This code provides security utility functions and configurations for handling...

August 27, 2025 at 04:25 AM

import os from datetime import datetime, timedelta from typing import Optional, Dict from jose import JWTError, jwt from passlib.context import CryptContext from dotenv import load_dotenv from datetime import UTC load_dotenv() JWT_SECRET_KEY = os.environ.get('JWT_SECRET_KEY') if not JWT_SECRET_KEY: raise ValueError("JWT_SECRET_KEY environment variable is not set. This is a critical security risk") class SecurityConfig: JWT_SECRET_KEY = JWT_SECRET_KEY JWT_ALGORITHM = "HS256" JWT_ACCESS_TOKEN_EXPIRES = int(os.environ.get('ACCESS_TOKEN_EXPIRE_MINUTES', 1440)) BCRYPT_LOG_ROUNDS = int(os.environ.get('BCRYPT_LOG_ROUNDS', 12)) SESSION_COOKIE_SECURE = os.environ.get('FLASK_ENV') == 'production' SESSION_COOKIE_HTTPONLY = True SESSION_COOKIE_SAMESITE = "Lax" CORS_ORIGINS = os.environ.get('CORS_ORIGINS', 'http://localhost:3000'). split(',') pwd_context = CryptContext( schemes=["bcrypt"], deprecated="auto", rounds=SecurityConfig.BCRYPT_LOG_ROUNDS ) def verify_password(plain_password: str, hashed_password: str) -> bool: return pwd_context.verify(plain_password, hashed_password) def get_password_hash(password: str) -> str: return pwd_context.hash(password) def create_access_token(data: Dict, expires_delta: Optional[timedelta] = None) -> str: """ Args: data (Dict): The payload data to encode in the token. expires_delta (Optional[timedelta]): The expiration time. If None, the default from Security Config is being used. Returns: str: The encoded JWT token """ to_encode = data.copy() expire = datetime.datetime.now(datetime.UTC) + (expires_delta or timedelta(minutes=SecurityConfig.ACCESS_TOKEN_EXPIRE_MINUTES)) to_encode.update({"exp": expire}) encoded_jwt = jwt.encode( to_encode, SecurityConfig.JWT_SECRET_KEY, algorithm=SecurityConfig.JWT_ALGORITHM ) return encoded_jwt def verify_token(token: str) -> Optional[Dict]: """ Decodes and veifies a JWT token. Args: token (str): The JWT token to veirfy. Returns: Optional[dict]: The payload of the token if valid, otherwise None. """ try: payload = jwt.decode( token, SecurityConfig.JWT_SECRET_KEY, algorithms=[SecurityConfig.JWT_ALGORITHM] ) return payload except JWTError: return None

This code provides security utility functions and configurations for handling password hashing and JSON Web Token (JWT) management in a Python application. Here's what it does step by step:

1. Environment Setup

  • load_dotenv() loads environment variables from a .env file into the program.
  • The code fetches the JWT_SECRET_KEY environment variable, which is used as the secret key for creating and verifying JWT tokens. If not set, a ValueError is raised because this key is critical for secure token handling.

2. Security Configuration

  • A SecurityConfig class defines key configuration settings such as:
    • JWT_SECRET_KEY: The secret key for signing JWTs.
    • JWT_ALGORITHM: The algorithm used for signing JWTs (HS256 in this case).
    • JWT_ACCESS_TOKEN_EXPIRES: Default expiration time (in minutes) for JWT access tokens.
    • BCRYPT_LOG_ROUNDS: Number of rounds used for bcrypt hashing to secure passwords.
    • SESSION_COOKIE_SECURE, SESSION_COOKIE_HTTPONLY, and SESSION_COOKIE_SAMESITE: Cookie-related settings for additional session security.
    • CORS_ORIGINS: List of allowed origins for Cross-Origin Resource Sharing (CORS).

3. Password Hashing

  • A CryptContext object (pwd_context) is created to manage password hashing with bcrypt.
    • Passwords are hashed with the get_password_hash() function using bcrypt.
    • Passwords can be verified with the verify_password() function, which compares a plaintext password to its hashed version.

4. JWT Token Creation

  • create_access_token(data, expires_delta):
    • Takes payload data (data) and an optional expiration time (expires_delta).
    • The token expiration time is set to either the default value (ACCESS_TOKEN_EXPIRE_MINUTES) or the specified expires_delta.
    • Encodes the payload and expiration time into a JWT using the HS256 algorithm and the secret key.

5. JWT Token Verification

  • verify_token(token):
    • Decodes and verifies a JWT token using the secret key and algorithm.
    • If the token is valid, it returns the payload as a dictionary.
    • If the token is invalid (e.g., tampered with, expired, or otherwise fails validation), it returns None.

6. Error Handling

  • If a JWT cannot be decoded or validated due to a JWTError, the verify_token() function catches the error and returns None.

Use Case:

This code provides:

  • A secure mechanism for hashing passwords and verifying them during authentication processes.
  • The ability to issue signed JWTs for access token generation.
  • A method to validate and decode received JWTs, ensuring only valid tokens are accepted.

In short, it is part of an authentication framework often used in REST APIs to manage user authentication and authorization securely.

Generate your own explanations
Download our vscode extension
Read other generated explanations

Built by @thebuilderjr
Sponsored by beam analytics
Read our terms and privacy policy
Forked from openai-quickstart-node