taskflow-api / src /core /security.py
suhail
good
0ff84fe
raw
history blame
6.69 kB
# """Security utilities for authentication and authorization."""
# import jwt
# from datetime import datetime, timedelta
# from passlib.context import CryptContext
# from fastapi import HTTPException, status
# from typing import Optional
# # Password hashing context
# pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
# def hash_password(password: str) -> str:
# if len(password.encode("utf-8")) > 72:
# raise HTTPException(
# status_code=status.HTTP_400_BAD_REQUEST,
# detail="Password must be at most 72 characters"
# )
# return pwd_context.hash(password)
# def verify_password(plain_password: str, hashed_password: str) -> bool:
# """
# Verify a password against its hash.
# Args:
# plain_password: Plain text password to verify
# hashed_password: Hashed password to compare against
# Returns:
# True if password matches, False otherwise
# """
# return pwd_context.verify(plain_password, hashed_password)
# def create_jwt_token(user_id: int, email: str, secret: str, expiration_days: int = 7) -> str:
# """
# Create a JWT token for a user.
# Args:
# user_id: User's unique identifier
# email: User's email address
# secret: Secret key for signing the token
# expiration_days: Number of days until token expires (default: 7)
# Returns:
# Encoded JWT token string
# """
# now = datetime.utcnow()
# payload = {
# "sub": str(user_id),
# "email": email,
# "iat": now,
# "exp": now + timedelta(days=expiration_days),
# "iss": "better-auth"
# }
# return jwt.encode(payload, secret, algorithm="HS256")
# def verify_jwt_token(token: str, secret: str) -> dict:
# """
# Verify and decode a JWT token.
# Args:
# token: JWT token string to verify
# secret: Secret key used to sign the token
# Returns:
# Decoded token payload as dictionary
# Raises:
# HTTPException: 401 if token is expired or invalid
# """
# try:
# payload = jwt.decode(
# token,
# secret,
# algorithms=["HS256"],
# options={
# "verify_signature": True,
# "verify_exp": True,
# "require": ["sub", "email", "iat", "exp", "iss"]
# }
# )
# # Validate issuer
# if payload.get("iss") != "better-auth":
# raise HTTPException(
# status_code=status.HTTP_401_UNAUTHORIZED,
# detail="Invalid token issuer",
# headers={"WWW-Authenticate": "Bearer"}
# )
# return payload
# except jwt.ExpiredSignatureError:
# raise HTTPException(
# status_code=status.HTTP_401_UNAUTHORIZED,
# detail="Token has expired",
# headers={"WWW-Authenticate": "Bearer"}
# )
# except jwt.InvalidTokenError:
# raise HTTPException(
# status_code=status.HTTP_401_UNAUTHORIZED,
# detail="Invalid token",
# headers={"WWW-Authenticate": "Bearer"}
# )
"""
Security utilities for authentication and authorization.
"""
from datetime import datetime, timedelta
from typing import Dict, Any
import jwt
from passlib.context import CryptContext
from fastapi import HTTPException, status, Depends
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from src.core.config import settings
# =========================
# Password hashing (bcrypt-safe)
# =========================
pwd_context = CryptContext(
schemes=["bcrypt"],
deprecated="auto"
)
security = HTTPBearer()
MAX_BCRYPT_BYTES = 72
def _bcrypt_safe(password: str) -> bytes:
"""
Ensure password never exceeds bcrypt 72-byte limit.
"""
return password.encode("utf-8")[:MAX_BCRYPT_BYTES]
def hash_password(password: str) -> str:
"""
Hash password safely using bcrypt.
"""
return pwd_context.hash(_bcrypt_safe(password))
def verify_password(plain_password: str, hashed_password: str) -> bool:
"""
Verify password safely.
Never throws bcrypt length errors.
"""
try:
return pwd_context.verify(
_bcrypt_safe(plain_password),
hashed_password
)
except Exception:
return False
# =========================
# JWT utilities
# =========================
def create_jwt_token(
user_id: int,
email: str,
secret: str,
expiration_days: int = 7
) -> str:
now = datetime.utcnow()
payload = {
"sub": str(user_id),
"email": email,
"iat": now,
"exp": now + timedelta(days=expiration_days),
"iss": "better-auth",
}
return jwt.encode(payload, secret, algorithm="HS256")
def verify_jwt_token(token: str, secret: str) -> dict:
try:
payload = jwt.decode(
token,
secret,
algorithms=["HS256"],
options={"verify_exp": True},
)
if payload.get("iss") != "better-auth":
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid token issuer"
)
return payload
except jwt.ExpiredSignatureError:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Token expired"
)
except jwt.InvalidTokenError:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid token"
)
# =========================
# FastAPI dependency
# =========================
def get_current_user(
credentials: HTTPAuthorizationCredentials = Depends(security)
) -> Dict[str, Any]:
"""
Extract and validate JWT token from Authorization header.
"""
token = credentials.credentials
try:
payload = verify_jwt_token(token, settings.BETTER_AUTH_SECRET)
user_id = int(payload.get("sub"))
return {
"id": user_id,
"email": payload.get("email"),
"iat": payload.get("iat"),
"exp": payload.get("exp"),
}
except ValueError:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid user ID in token",
headers={"WWW-Authenticate": "Bearer"},
)
except Exception as e:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail=f"Authentication failed: {str(e)}",
headers={"WWW-Authenticate": "Bearer"},
)