from rest_framework import authentication from rest_framework.request import Request from rest_framework import exceptions from django.utils.translation import gettext_lazy as _ from labs.models import APIKey class SessionAuthentication(authentication.SessionAuthentication): """ Django REST framework's default SessionAuthentication return 403 instead of 401 when user is not logged in, beacuse it does not include `WWW-Authenticate` header, this class is a workaround to fix this issue. """ def authenticate_header(self, request: Request) -> str: return 'xBasic realm="cookie"' # def enforce_csrf(self, request: Request) -> None: # # TODO: remove this override, we need csrf protection # pass class APIKeyAuthentication(authentication.TokenAuthentication): keyword = "Bearer" def authenticate_credentials(self, key): try: api_key_obj = APIKey.objects.get_by_raw_key(key) except APIKey.DoesNotExist: raise exceptions.AuthenticationFailed(_("Invalid token.")) if not api_key_obj.user.is_active: raise exceptions.AuthenticationFailed(_("User inactive or deleted.")) return (api_key_obj.user, key)