webmentai / middleware /get_current_user.py
subhandev1
Deploy FastAPI backend with Brevo email, contact form, and SEO reports
f5e7f79
Raw
History Blame Contribute Delete
1.37 kB
from fastapi import HTTPException, Request
from jose import jwt, JWTError
from dotenv import load_dotenv
from reports.database import db
from bson import ObjectId
import os
load_dotenv()
SECRET_KEY = os.getenv("SECRET_KEY")
ALGORITHM = os.getenv("ALGORITHM")
async def get_current_user(request: Request):
auth_header = request.headers.get("Authorization")
if not auth_header or not auth_header.startswith("Bearer "):
raise HTTPException(status_code=401, detail="Invalid token format")
token = auth_header.split(" ")[1]
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
user_id: str = payload.get("sub")
if user_id is None:
raise HTTPException(status_code=401, detail="Invalid token")
user = await db["users"].find_one({"_id": ObjectId(user_id)})
if not user:
raise HTTPException(status_code=401, detail="User not found")
# ✅ Block access if email is not verified OR status is not active
if not user.get("is_verified", False) or user.get("status") != "active":
raise HTTPException(
status_code=403,
detail="Email not verified. Please verify your email first."
)
return user
except JWTError:
raise HTTPException(status_code=401, detail="Invalid token")