/security-auditor skills changes done
This commit is contained in:
47
backend/auth.py
Normal file
47
backend/auth.py
Normal file
@@ -0,0 +1,47 @@
|
||||
"""Firebase token verification and ownership helpers."""
|
||||
import logging
|
||||
from fastapi import HTTPException, Header
|
||||
from firebase_admin import auth as firebase_auth
|
||||
import firebase_admin
|
||||
from bson import ObjectId
|
||||
from bson.errors import InvalidId
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
async def get_current_user(authorization: str = Header(..., alias="Authorization")) -> dict:
|
||||
"""FastAPI dependency: verifies Firebase ID token and returns decoded payload."""
|
||||
if not authorization.startswith("Bearer "):
|
||||
raise HTTPException(status_code=401, detail="Invalid authorization header")
|
||||
|
||||
token = authorization[len("Bearer "):]
|
||||
|
||||
if not firebase_admin._apps:
|
||||
raise HTTPException(status_code=503, detail="Authentication service unavailable")
|
||||
|
||||
try:
|
||||
return firebase_auth.verify_id_token(token)
|
||||
except firebase_auth.ExpiredIdTokenError:
|
||||
raise HTTPException(status_code=401, detail="Token expired")
|
||||
except Exception:
|
||||
raise HTTPException(status_code=401, detail="Invalid token")
|
||||
|
||||
|
||||
def verify_user_access(user_id: str, db, token: dict) -> dict:
|
||||
"""
|
||||
Fetch user by ObjectId and confirm the token owner matches.
|
||||
Returns the user document. Raises 400/404/403 on failure.
|
||||
"""
|
||||
try:
|
||||
user_oid = ObjectId(user_id)
|
||||
except InvalidId:
|
||||
raise HTTPException(status_code=400, detail="Invalid user ID format")
|
||||
|
||||
user = db.users.find_one({"_id": user_oid})
|
||||
if not user:
|
||||
raise HTTPException(status_code=404, detail="User not found")
|
||||
|
||||
if user.get("email") != token.get("email"):
|
||||
raise HTTPException(status_code=403, detail="Access denied")
|
||||
|
||||
return user
|
||||
Reference in New Issue
Block a user