auth.py 1.1 KB

123456789101112131415161718192021222324252627
  1. from apps.web.models.users import Users
  2. from fastapi import Request, status
  3. from starlette.authentication import (
  4. AuthCredentials, AuthenticationBackend, AuthenticationError,
  5. )
  6. from starlette.requests import HTTPConnection
  7. from utils.utils import verify_token
  8. from starlette.responses import JSONResponse
  9. from constants import ERROR_MESSAGES
  10. class BearerTokenAuthBackend(AuthenticationBackend):
  11. async def authenticate(self, conn: HTTPConnection):
  12. if "Authorization" not in conn.headers:
  13. return
  14. data = verify_token(conn)
  15. if data != None and 'email' in data:
  16. user = Users.get_user_by_email(data['email'])
  17. if user is None:
  18. raise AuthenticationError('Invalid credentials')
  19. return AuthCredentials([user.role]), user
  20. else:
  21. raise AuthenticationError('Invalid credentials')
  22. def on_auth_error(request: Request, exc: Exception):
  23. print('Authentication failed: ', exc)
  24. return JSONResponse({"detail": ERROR_MESSAGES.INVALID_TOKEN}, status_code=status.HTTP_401_UNAUTHORIZED)