2026-05-31 20:36:42 +00:00
|
|
|
"""Security helpers: password hashing and JWT token management."""
|
|
|
|
|
|
|
|
|
|
from datetime import datetime, timedelta, timezone
|
|
|
|
|
from typing import Any
|
|
|
|
|
|
2026-05-31 20:49:10 +00:00
|
|
|
import bcrypt
|
2026-05-31 20:36:42 +00:00
|
|
|
from jose import jwt
|
|
|
|
|
|
|
|
|
|
from app.core.config import settings
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def verify_password(plain_password: str, hashed_password: str) -> bool:
|
|
|
|
|
"""Verify a plaintext password against a bcrypt hash."""
|
2026-05-31 20:49:10 +00:00
|
|
|
return bcrypt.checkpw(
|
|
|
|
|
plain_password.encode("utf-8"), hashed_password.encode("utf-8")
|
|
|
|
|
)
|
2026-05-31 20:36:42 +00:00
|
|
|
|
|
|
|
|
|
|
|
|
|
def get_password_hash(password: str) -> str:
|
|
|
|
|
"""Hash a password using bcrypt."""
|
2026-05-31 20:49:10 +00:00
|
|
|
return bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt()).decode("utf-8")
|
2026-05-31 20:36:42 +00:00
|
|
|
|
|
|
|
|
|
2026-06-10 21:31:41 +00:00
|
|
|
def create_access_token(
|
|
|
|
|
subject: str | Any, expires_delta: timedelta | None = None
|
|
|
|
|
) -> str:
|
2026-05-31 20:36:42 +00:00
|
|
|
"""Create a short-lived JWT access token."""
|
|
|
|
|
if expires_delta is None:
|
|
|
|
|
expires_delta = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
|
|
|
|
|
now = datetime.now(timezone.utc)
|
|
|
|
|
expire = now + expires_delta
|
|
|
|
|
to_encode = {"exp": expire, "sub": str(subject), "iat": now, "type": "access"}
|
2026-06-10 21:31:41 +00:00
|
|
|
return jwt.encode(
|
|
|
|
|
to_encode, settings.JWT_SECRET_KEY, algorithm=settings.JWT_ALGORITHM
|
|
|
|
|
)
|
2026-05-31 20:36:42 +00:00
|
|
|
|
|
|
|
|
|
2026-06-10 21:31:41 +00:00
|
|
|
def create_refresh_token(
|
|
|
|
|
subject: str | Any, expires_delta: timedelta | None = None
|
|
|
|
|
) -> str:
|
2026-05-31 20:36:42 +00:00
|
|
|
"""Create a long-lived JWT refresh token."""
|
|
|
|
|
if expires_delta is None:
|
|
|
|
|
expires_delta = timedelta(minutes=settings.REFRESH_TOKEN_EXPIRE_MINUTES)
|
|
|
|
|
now = datetime.now(timezone.utc)
|
|
|
|
|
expire = now + expires_delta
|
|
|
|
|
to_encode = {"exp": expire, "sub": str(subject), "iat": now, "type": "refresh"}
|
2026-06-10 21:31:41 +00:00
|
|
|
return jwt.encode(
|
|
|
|
|
to_encode, settings.JWT_SECRET_KEY, algorithm=settings.JWT_ALGORITHM
|
|
|
|
|
)
|
2026-05-31 20:36:42 +00:00
|
|
|
|
|
|
|
|
|
|
|
|
|
def verify_token(token: str) -> dict:
|
|
|
|
|
"""Decode and verify a JWT token. Returns the payload dict."""
|
2026-06-10 21:31:41 +00:00
|
|
|
return jwt.decode(
|
|
|
|
|
token, settings.JWT_SECRET_KEY, algorithms=[settings.JWT_ALGORITHM]
|
|
|
|
|
)
|