Files
poona-ams/backend/app/core/security.py
T

104 lines
3.5 KiB
Python

from datetime import timedelta
import bcrypt
from fastapi import HTTPException, status
from jose import JWTError, jwt
from .config import settings
from .time_utils import utc_now
BLOCKLIST_PASSWORDS = {
"123456",
"12345678",
"password",
"password1",
"qwerty123",
"admin123",
"welcome1",
}
def validate_password(password: str, email: str | None = None) -> None:
"""Validate password rules:
- Length: at least 8, at most 128 characters.
- Characters: at least one letter and at least one digit. (Special characters allowed, not required. Case insensitive.)
- Must NOT start or end with a space (reject with a clear message, do not silently strip).
- Blocklist (case-insensitive): '123456', '12345678', 'password', 'password1', 'qwerty123', 'admin123', 'welcome1'.
(NOTE: demo password 'demo@123' must remain allowed)
- Must not contain the user's username/email local-part if length >= 4 (case-insensitive).
"""
if not isinstance(password, str):
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail="Password must be a string.",
)
if password.startswith(" ") or password.endswith(" "):
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail="Password must not start or end with a space.",
)
if len(password) < 8:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail="Password must be at least 8 characters long.",
)
if len(password) > 128:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail="Password must be at most 128 characters long.",
)
has_letter = any(c.isalpha() for c in password)
has_digit = any(c.isdigit() for c in password)
if not has_letter or not has_digit:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail="Password must contain at least one letter and at least one digit.",
)
lower_pass = password.lower()
if lower_pass in BLOCKLIST_PASSWORDS:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail="Password is too common or easily guessable.",
)
if email:
local_part = email.split("@")[0].strip().lower()
if len(local_part) >= 4 and local_part in lower_pass:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail="Password must not contain your email username.",
)
def verify_password(plain: str, hashed: str) -> bool:
if not plain or not hashed:
return False
try:
return bcrypt.checkpw(
plain.encode("utf-8")[:72],
hashed.encode("utf-8"),
)
except ValueError:
return False
def hash_password(plain: str) -> str:
hashed = bcrypt.hashpw(plain.encode("utf-8")[:72], bcrypt.gensalt())
return hashed.decode("utf-8")
def create_access_token(data: dict, expires_minutes: int | None = None) -> str:
to_encode = data.copy()
if "tv" not in to_encode:
to_encode["tv"] = 0
expire = utc_now() + timedelta(minutes=expires_minutes or settings.ACCESS_TOKEN_EXPIRE_MINUTES)
to_encode["exp"] = expire
return jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM)
def decode_token(token: str) -> dict:
return jwt.decode(token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM])