Reoraganized project
This commit is contained in:
@@ -0,0 +1,43 @@
|
||||
import jwt
|
||||
from django.conf import settings
|
||||
from rest_framework.authentication import (
|
||||
BaseAuthentication,
|
||||
)
|
||||
from rest_framework.exceptions import AuthenticationFailed, NotAuthenticated
|
||||
from rest_framework.permissions import IsAuthenticated
|
||||
|
||||
from api.users.models import Profile
|
||||
|
||||
|
||||
class JWTAuthentication(BaseAuthentication):
|
||||
def authenticate_header(self, request):
|
||||
return "Provide a valid token in the 'Authorization' header"
|
||||
|
||||
def authenticate(self, request):
|
||||
token = request.headers.get("Authorization", "").split("Bearer ")[-1]
|
||||
|
||||
if not token:
|
||||
if IsAuthenticated in getattr(
|
||||
request.resolver_match.func.cls, "permission_classes", []
|
||||
):
|
||||
raise NotAuthenticated
|
||||
|
||||
return None
|
||||
|
||||
try:
|
||||
payload = jwt.decode(
|
||||
token, settings.SECRET_KEY, algorithms=["HS256"]
|
||||
)
|
||||
|
||||
user = Profile.objects.get(id=payload["id"])
|
||||
except Profile.DoesNotExist:
|
||||
error = "Invalid token"
|
||||
raise AuthenticationFailed(error) from None
|
||||
except jwt.ExpiredSignatureError:
|
||||
error = "Token has expired"
|
||||
raise AuthenticationFailed(error) from None
|
||||
except jwt.InvalidTokenError:
|
||||
error = "Invalid token"
|
||||
raise AuthenticationFailed(error) from None
|
||||
else:
|
||||
return (user, None)
|
||||
Reference in New Issue
Block a user