from __future__ import annotations import base64 import hashlib import hmac import json import os import re import secrets import string import time from typing import Any import bcrypt from .errors import InvalidEmailError, InvalidTokenError, WeakPasswordError DEFAULT_JWT_SECRET = "panacea-secret-key-for-jwt-token-generation" JWT_SECRET = os.getenv("JWT_SECRET", DEFAULT_JWT_SECRET) JWT_TTL_SECONDS = int(os.getenv("JWT_TTL_SECONDS", str(86400 * 7))) EMAIL_REGEX = re.compile(r"^[^\s@]+@[^\s@]+\.[^\s@]+$") def base64url_encode(data: bytes) -> str: return base64.urlsafe_b64encode(data).rstrip(b"=").decode("ascii") def base64url_decode(data: str) -> bytes: padding = "=" * (-len(data) % 4) return base64.urlsafe_b64decode(data + padding) def normalize_email(value: str) -> str: email = value.strip().lower() if not EMAIL_REGEX.fullmatch(email): raise InvalidEmailError( "Please enter a valid email address (e.g. user@example.com)." ) return email def normalize_phone_number(value: str | None) -> str: return value.strip() if value else "" def validate_password_strength(password: str) -> None: if len(password) < 8: raise WeakPasswordError( "Password must be at least 8 characters long." ) if not any(c.isupper() for c in password): raise WeakPasswordError( "Password must contain at least one uppercase letter." ) if not any(c.isdigit() for c in password): raise WeakPasswordError( "Password must contain at least one number." ) if not any(c in string.punctuation for c in password): raise WeakPasswordError( "Password must contain at least one special character." ) def hash_password(password: str) -> str: """bcrypt is the only supported password format.""" return bcrypt.hashpw( password.encode("utf-8"), bcrypt.gensalt(), ).decode("utf-8") def verify_password(password: str, encoded_hash: str | None) -> bool: """Verify bcrypt only; no legacy hash compatibility is retained.""" if not encoded_hash: return False if not encoded_hash.startswith(("$2b$", "$2a$", "$2y$")): return False try: return bcrypt.checkpw( password.encode("utf-8"), encoded_hash.encode("utf-8"), ) except (TypeError, ValueError): return False def generate_otp_code() -> str: return f"{secrets.randbelow(1_000_000):06d}" def create_access_token(data: dict[str, Any]) -> str: header = {"alg": "HS256", "typ": "JWT"} payload = dict(data) payload["exp"] = int(time.time()) + JWT_TTL_SECONDS header_b64 = base64url_encode( json.dumps(header, separators=(",", ":")).encode("utf-8") ) payload_b64 = base64url_encode( json.dumps(payload, separators=(",", ":")).encode("utf-8") ) signing_input = f"{header_b64}.{payload_b64}".encode("utf-8") signature = hmac.new( JWT_SECRET.encode("utf-8"), signing_input, hashlib.sha256, ).digest() return ( f"{header_b64}.{payload_b64}." f"{base64url_encode(signature)}" ) def decode_access_token(token: str) -> dict[str, Any]: try: header_b64, payload_b64, signature_b64 = token.split(".") except ValueError as exc: raise InvalidTokenError("Unauthorized.") from exc signing_input = f"{header_b64}.{payload_b64}".encode("utf-8") expected_signature = hmac.new( JWT_SECRET.encode("utf-8"), signing_input, hashlib.sha256, ).digest() try: supplied_signature = base64url_decode(signature_b64) header = json.loads( base64url_decode(header_b64).decode("utf-8") ) payload = json.loads( base64url_decode(payload_b64).decode("utf-8") ) except Exception as exc: raise InvalidTokenError("Unauthorized.") from exc if not hmac.compare_digest( expected_signature, supplied_signature, ): raise InvalidTokenError("Unauthorized.") if header.get("alg") != "HS256" or header.get("typ") != "JWT": raise InvalidTokenError("Unauthorized.") exp = payload.get("exp") if not isinstance(exp, int) or exp <= int(time.time()): raise InvalidTokenError("Unauthorized.") sub = payload.get("sub") if not isinstance(sub, str) or not sub: raise InvalidTokenError("Unauthorized.") return payload