hfcron / backend /api /dependencies.py
Ajitdoval's picture
Create backend/api/dependencies.py
4e51523 verified
Raw
History Blame Contribute Delete
1.41 kB
from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
import jwt
from backend.core.config import settings
from backend.core.database import get_database
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="auth/verify-otp")
async def get_current_user(token: str = Depends(oauth2_scheme)):
credentials_exception = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
headers={"WWW-Authenticate": "Bearer"},
)
try:
# Decode the JWT token
payload = jwt.decode(token, settings.JWT_SECRET, algorithms=[settings.JWT_ALGORITHM])
telegram_id: str = payload.get("sub")
if telegram_id is None:
raise credentials_exception
except jwt.PyJWTError:
raise credentials_exception
# Check if user exists in MongoDB
db = get_database()
user = await db["users"].find_one({"telegram_id": telegram_id})
if user is None:
raise credentials_exception
return user
async def get_admin_user(current_user: dict = Depends(get_current_user)):
"""Dependency to enforce admin-only routes."""
if not current_user.get("is_admin"):
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Not enough privileges to access this route"
)
return current_user