You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

33 lines
927 B

from typing import Any
import jwt
from django.conf import settings
from django.contrib.auth.models import User, AnonymousUser
from django.http import HttpRequest
from strawberry import BasePermission
from strawberry.extensions import Extension
from strawberry.types import Info
class GraphQLError(Exception):
pass
class AuthExtension(Extension):
def on_request_start(self):
request = self.execution_context.context.request
auth = request.headers.get('authorization')
if auth:
try:
payload = jwt.decode(auth, settings.SECRET_KEY, algorithms=['HS256'])
self.execution_context.context.user = User.objects.get(pk=payload['id'])
return
except (jwt.DecodeError, User.DoesNotExist):
pass
self.execution_context.context.user = AnonymousUser()
class IsAuthenticated(BasePermission):
def has_permission(self, source: Any, info: Info, **kwargs) -> bool:
return info.context.user.is_authenticated