34 lines
1.1 KiB
Python
34 lines
1.1 KiB
Python
"""Authentication utilities and dependencies."""
|
|
import jwt
|
|
from fastapi import Request, HTTPException
|
|
import config as config_module
|
|
|
|
|
|
def get_current_user(request: Request) -> dict:
|
|
"""Dependency to check authentication and return user info"""
|
|
token = request.cookies.get("auth_token")
|
|
|
|
if not token:
|
|
raise HTTPException(status_code=401, detail="Not authenticated")
|
|
|
|
try:
|
|
payload = jwt.decode(token, config_module.JWT_SECRET, algorithms=["HS256"])
|
|
return payload
|
|
except jwt.ExpiredSignatureError:
|
|
raise HTTPException(status_code=401, detail="Token expired")
|
|
except jwt.InvalidTokenError:
|
|
raise HTTPException(status_code=401, detail="Invalid token")
|
|
|
|
|
|
def check_auth(request: Request) -> bool:
|
|
"""Check if user is authenticated (returns bool, doesn't raise exception)"""
|
|
token = request.cookies.get("auth_token")
|
|
if not token:
|
|
return False
|
|
|
|
try:
|
|
jwt.decode(token, config_module.JWT_SECRET, algorithms=["HS256"])
|
|
return True
|
|
except (jwt.ExpiredSignatureError, jwt.InvalidTokenError):
|
|
return False
|