9c92d39629
- verify_password catches ValueError from passlib so a mangled hash ($ signs stripped by shell/Docker) returns False instead of crashing - Settings.check_password_hash logs a clear startup error with fix instructions when AUTH_PASSWORD_HASH doesn't start with '$2'
35 lines
1.0 KiB
Python
35 lines
1.0 KiB
Python
from datetime import datetime, timedelta, timezone
|
|
|
|
from jose import JWTError, jwt
|
|
from passlib.context import CryptContext
|
|
|
|
from app.core.config import settings
|
|
|
|
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
|
|
|
|
|
def verify_password(plain: str, hashed: str) -> bool:
|
|
try:
|
|
return bool(pwd_context.verify(plain, hashed))
|
|
except ValueError:
|
|
return False
|
|
|
|
|
|
def hash_password(password: str) -> str:
|
|
return str(pwd_context.hash(password))
|
|
|
|
|
|
def create_access_token(subject: str) -> str:
|
|
expire = datetime.now(timezone.utc) + timedelta(minutes=settings.access_token_expire_minutes)
|
|
payload = {"sub": subject, "exp": expire}
|
|
return str(jwt.encode(payload, settings.secret_key, algorithm=settings.algorithm))
|
|
|
|
|
|
def decode_token(token: str) -> str | None:
|
|
try:
|
|
payload = jwt.decode(token, settings.secret_key, algorithms=[settings.algorithm])
|
|
sub = payload.get("sub")
|
|
return str(sub) if sub is not None else None
|
|
except JWTError:
|
|
return None
|