Files
mft/mft/auth.py

47 lines
1.2 KiB
Python

from fastapi import Depends, HTTPException, status
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from mft.database import get_db
import hashlib
security = HTTPBearer()
def verify_token(
credentials: HTTPAuthorizationCredentials = Depends(security),
) -> int:
"""
Verify bearer token and return user ID.
Args:
credentials: The HTTP authorization credentials containing the bearer token
Returns:
The user ID associated with the valid token
Raises:
HTTPException: If token is invalid or disabled
"""
token = credentials.credentials
token_hash = hashlib.sha256(token.encode()).hexdigest()
with get_db() as conn:
cursor = conn.cursor()
result = cursor.execute(
"""
SELECT uid, enabled
FROM auth
WHERE token = ?
""",
(token_hash,),
).fetchone()
if result is None or not result["enabled"]:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid authentication token",
headers={"WWW-Authenticate": "Bearer"},
)
return result["uid"]