Add ApiTokenRequiredMixin
This commit is contained in:
parent
bec4b19366
commit
90b2896ded
24
shynet/api/mixins.py
Normal file
24
shynet/api/mixins.py
Normal file
@ -0,0 +1,24 @@
|
||||
from django.http import JsonResponse
|
||||
from django.contrib.auth.models import AnonymousUser
|
||||
from .models import ApiToken
|
||||
|
||||
|
||||
class ApiTokenRequiredMixin:
|
||||
def _get_user_by_token(self, request):
|
||||
token = request.headers.get('Authorization')
|
||||
if not token or not token.startswith('Token '):
|
||||
return AnonymousUser()
|
||||
|
||||
token = token.split(' ')[1]
|
||||
api_token = ApiToken.objects.filter(value=token).first()
|
||||
if not api_token:
|
||||
return AnonymousUser()
|
||||
|
||||
return api_token.user
|
||||
|
||||
def dispatch(self, request, *args, **kwargs):
|
||||
request.user = self._get_user_by_token(request)
|
||||
if not request.user.is_authenticated:
|
||||
return JsonResponse(data={}, status=403)
|
||||
|
||||
return super().dispatch(request, *args, **kwargs)
|
Loading…
Reference in New Issue
Block a user