acupedia-api/app/features/auth/security.py

275 lines
8.8 KiB
Python

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"^[a-zA-Z0-9_%+-]+(?:\.[a-zA-Z0-9_%+-]+)*@[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?)*\.[a-zA-Z]{2,}$"
)
MIN_NATIONAL_PHONE_DIGITS = 6
# Prefix-free ITU-T E.164 country calling codes (1 to 3 digits).
ITU_CALLING_CODES: frozenset[str] = frozenset({
"1", "7",
"20", "27", "30", "31", "32", "33", "34", "36", "39", "40", "41", "43",
"44", "45", "46", "47", "48", "49", "51", "52", "53", "54", "55", "56",
"57", "58", "60", "61", "62", "63", "64", "65", "66", "81", "82", "84",
"86", "90", "91", "92", "93", "94", "95", "98",
"211", "212", "213", "216", "218",
"220", "221", "222", "223", "224", "225", "226", "227", "228", "229",
"230", "231", "232", "233", "234", "235", "236", "237", "238", "239",
"240", "241", "242", "243", "244", "245", "246", "247", "248", "249",
"250", "251", "252", "253", "254", "255", "256", "257", "258",
"260", "261", "262", "263", "264", "265", "266", "267", "268", "269",
"290", "291", "297", "298", "299",
"350", "351", "352", "353", "354", "355", "356", "357", "358", "359",
"370", "371", "372", "373", "374", "375", "376", "377", "378", "379",
"380", "381", "382", "383", "385", "386", "387", "389",
"420", "421", "423",
"500", "501", "502", "503", "504", "505", "506", "507", "508", "509",
"590", "591", "592", "593", "594", "595", "596", "597", "598", "599",
"670", "672", "673", "674", "675", "676", "677", "678", "679",
"680", "681", "682", "683", "685", "686", "687", "688", "689",
"690", "691", "692",
"850", "852", "853", "855", "856", "880", "886",
"960", "961", "962", "963", "964", "965", "966", "967", "968",
"970", "971", "972", "973", "974", "975", "976", "977",
"992", "993", "994", "995", "996", "998",
})
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 extract_phone_digits(value: str | None) -> str:
"""Return only ASCII digits from a phone string."""
if not value:
return ""
return "".join(ch for ch in value if ch.isdigit())
def _split_e164_digits(digits: str, local: str) -> bool:
"""Return True when ``digits`` equals ``<ITU_CALLING_CODE><local>``."""
if len(local) < MIN_NATIONAL_PHONE_DIGITS or len(digits) <= len(local):
return False
if not digits.endswith(local):
return False
prefix = digits[: -len(local)]
return prefix in ITU_CALLING_CODES
def build_phone_lookup_variants(
value: str | None,
) -> tuple[tuple[str, ...], tuple[str, ...]]:
"""Build exact equality values and national suffix digits for login phone lookup."""
stripped = normalize_phone_number(value)
if not stripped:
return (), ()
digits = extract_phone_digits(stripped)
compact = re.sub(r"[\s\-()]+", "", stripped)
exact_candidates: list[str] = []
for candidate in (stripped, compact, f"+{digits}" if digits else ""):
if candidate and candidate not in exact_candidates:
exact_candidates.append(candidate)
suffix_candidates: list[str] = []
if digits and not stripped.startswith("+"):
national = digits.lstrip("0") or digits
for suffix in (digits, national):
if len(suffix) >= MIN_NATIONAL_PHONE_DIGITS and suffix not in suffix_candidates:
suffix_candidates.append(suffix)
return tuple(exact_candidates), tuple(suffix_candidates)
def matches_login_phone(
stored_phone: str | None,
login_phone: str | None,
) -> bool:
"""
Determine whether ``stored_phone`` represents the same phone number as ``login_phone``.
Supports E.164 stored values (e.g. ``+917796701290``) when a user logs in
with a local/national number without a country code (e.g. ``7796701290`` or
``07796701290``), while rejecting partial-digit suffix collisions via prefix-free
ITU calling-code boundary checks.
"""
login_raw = normalize_phone_number(login_phone)
stored_raw = normalize_phone_number(stored_phone)
login_digits = extract_phone_digits(login_raw)
stored_digits = extract_phone_digits(stored_raw)
if not login_digits or not stored_digits:
return False
if login_raw.startswith("+"):
return stored_digits == login_digits
if stored_digits == login_digits:
return True
national = login_digits.lstrip("0") or login_digits
for candidate_local in (login_digits, national):
if _split_e164_digits(stored_digits, candidate_local):
return True
if not stored_raw.startswith("+"):
return _split_e164_digits(login_digits, stored_digits)
return False
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