File size: 1,340 Bytes
172064c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
from typing import Annotated
from fastapi import Depends
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from fastapi.responses import JSONResponse
from src.apis.providers.jwt_provider import jwt_provider as jwt
from src.apis.models.user_models import get_user
from src.config.mongo import UserCRUD
from bson import ObjectId
from jose import JWTError
from src.utils.logger import logger

security = HTTPBearer()


async def get_current_user(

    credentials: Annotated[HTTPAuthorizationCredentials, Depends(security)]

):

    try:
        token = credentials.credentials
        if not token:
            return JSONResponse(
                content={"msg": "Authentication failed"}, status_code=401
            )
        payload = jwt.decrypt(token)
        user_id: str = payload["id"]
        if not user_id:
            return JSONResponse(
                content={"msg": "Authentication failed"}, status_code=401
            )
        user = await UserCRUD.read_one({"_id": ObjectId(user_id)})
        if not user:
            return JSONResponse(
                content={"msg": "Authentication failed"}, status_code=401
            )
        return get_user(user)
    except JWTError:
        return JSONResponse(content={"msg": "Authentication failed"}, status_code=401)