2023-05-24 23:21:22 +03:00
|
|
|
import os
|
2023-06-17 00:36:53 +03:00
|
|
|
from typing import Optional
|
2023-05-24 23:21:22 +03:00
|
|
|
|
2023-06-17 00:36:53 +03:00
|
|
|
from auth.api_key_handler import get_user_from_api_key, verify_api_key
|
2023-06-14 22:21:13 +03:00
|
|
|
from auth.jwt_token_handler import decode_access_token, verify_token
|
2023-06-17 00:36:53 +03:00
|
|
|
from fastapi import Depends, HTTPException, Request
|
|
|
|
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
2023-06-14 22:21:13 +03:00
|
|
|
from models.users import User
|
2023-06-17 00:36:53 +03:00
|
|
|
from utils.common import CommonsDep
|
|
|
|
|
2023-05-24 23:21:22 +03:00
|
|
|
|
2023-06-14 22:21:13 +03:00
|
|
|
class AuthBearer(HTTPBearer):
|
2023-05-24 23:21:22 +03:00
|
|
|
def __init__(self, auto_error: bool = True):
|
|
|
|
super().__init__(auto_error=auto_error)
|
|
|
|
|
2023-06-14 22:21:13 +03:00
|
|
|
async def __call__(self, request: Request, commons: CommonsDep):
|
2023-05-24 23:21:22 +03:00
|
|
|
credentials: Optional[HTTPAuthorizationCredentials] = await super().__call__(request)
|
2023-06-14 22:21:13 +03:00
|
|
|
self.check_scheme(credentials)
|
|
|
|
token = credentials.credentials
|
|
|
|
return await self.authenticate(token, commons)
|
|
|
|
|
|
|
|
def check_scheme(self, credentials):
|
|
|
|
if credentials and not credentials.scheme == "Bearer":
|
|
|
|
raise HTTPException(status_code=402, detail="Invalid authorization scheme.")
|
|
|
|
elif not credentials:
|
2023-05-24 23:21:22 +03:00
|
|
|
raise HTTPException(status_code=403, detail="Invalid authorization code.")
|
|
|
|
|
2023-06-14 22:21:13 +03:00
|
|
|
async def authenticate(self, token: str, commons: CommonsDep):
|
|
|
|
if os.environ.get("AUTHENTICATE") == "false":
|
|
|
|
return self.get_test_user()
|
|
|
|
elif verify_token(token):
|
|
|
|
return decode_access_token(token)
|
|
|
|
elif await verify_api_key(token, commons):
|
|
|
|
return await get_user_from_api_key(token, commons)
|
|
|
|
else:
|
|
|
|
raise HTTPException(status_code=402, detail="Invalid token or expired token.")
|
2023-06-12 18:58:05 +03:00
|
|
|
|
2023-06-14 22:21:13 +03:00
|
|
|
def get_test_user(self):
|
|
|
|
return {'email': 'test@example.com'} # replace with test user information
|
2023-06-12 18:58:05 +03:00
|
|
|
|
2023-06-14 22:21:13 +03:00
|
|
|
def get_current_user(credentials: dict = Depends(AuthBearer())) -> User:
|
2023-06-12 18:58:05 +03:00
|
|
|
return User(email=credentials.get('email', 'none'))
|