from datetime import datetime, timedelta import bcrypt from bson import ObjectId from fastapi import Depends, HTTPException, Header from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials from jose import jwt, JWTError from app.config import settings from app.database import get_db security = HTTPBearer() def hash_password(password: str) -> str: return bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt()).decode("utf-8") def verify_password(plain: str, hashed: str) -> bool: return bcrypt.checkpw(plain.encode("utf-8"), hashed.encode("utf-8")) def create_access_token(user_id: str) -> str: expire = datetime.utcnow() + timedelta(hours=settings.JWT_EXPIRY_HOURS) payload = {"sub": user_id, "exp": expire} return jwt.encode(payload, settings.JWT_SECRET, algorithm=settings.JWT_ALGORITHM) async def verify_api_key(x_api_key: str = Header(...)): if x_api_key != settings.API_KEY: raise HTTPException(status_code=401, detail="Invalid API key") return x_api_key async def get_current_user( credentials: HTTPAuthorizationCredentials = Depends(security), ): try: payload = jwt.decode( credentials.credentials, settings.JWT_SECRET, algorithms=[settings.JWT_ALGORITHM], ) user_id = payload.get("sub") if user_id is None: raise HTTPException(status_code=401, detail="Invalid token") except JWTError: raise HTTPException(status_code=401, detail="Invalid token") db = get_db() user = await db.users.find_one({"_id": ObjectId(user_id)}) if user is None: raise HTTPException(status_code=401, detail="User not found") return user