2023-05-24 23:21:22 +03:00
|
|
|
import os
|
2023-05-31 14:51:23 +03:00
|
|
|
from typing import Optional
|
2023-05-24 23:21:22 +03:00
|
|
|
|
2023-06-12 18:58:05 +03:00
|
|
|
from fastapi import HTTPException, Request, Depends
|
2023-05-31 14:51:23 +03:00
|
|
|
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
2023-06-12 18:58:05 +03:00
|
|
|
from models.users import User
|
2023-06-04 00:12:42 +03:00
|
|
|
from .auth_handler import decode_access_token
|
|
|
|
|
2023-05-24 23:21:22 +03:00
|
|
|
|
|
|
|
class JWTBearer(HTTPBearer):
|
|
|
|
def __init__(self, auto_error: bool = True):
|
|
|
|
super().__init__(auto_error=auto_error)
|
|
|
|
|
|
|
|
async def __call__(self, request: Request):
|
|
|
|
credentials: Optional[HTTPAuthorizationCredentials] = await super().__call__(request)
|
|
|
|
if os.environ.get("AUTHENTICATE") == "false":
|
|
|
|
return True
|
|
|
|
if credentials:
|
|
|
|
if not credentials.scheme == "Bearer":
|
|
|
|
raise HTTPException(status_code=402, detail="Invalid authorization scheme.")
|
|
|
|
token = credentials.credentials
|
|
|
|
if not self.verify_jwt(token):
|
|
|
|
raise HTTPException(status_code=402, detail="Invalid token or expired token.")
|
2023-05-31 14:51:23 +03:00
|
|
|
return self.verify_jwt(token) # change this line
|
2023-05-24 23:21:22 +03:00
|
|
|
else:
|
|
|
|
raise HTTPException(status_code=403, detail="Invalid authorization code.")
|
|
|
|
|
2023-05-31 14:51:23 +03:00
|
|
|
def verify_jwt(self, jwtoken: str):
|
2023-05-24 23:21:22 +03:00
|
|
|
payload = decode_access_token(jwtoken)
|
2023-06-12 18:58:05 +03:00
|
|
|
return payload
|
|
|
|
|
|
|
|
|
|
|
|
def get_current_user(credentials: dict = Depends(JWTBearer())) -> User:
|
|
|
|
return User(email=credentials.get('email', 'none'))
|