-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackends.py
63 lines (50 loc) · 2.08 KB
/
backends.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import jwt
from django.http import HttpResponse
from django.conf import settings
from rest_framework.authentication import get_authorization_header, BaseAuthentication
from rest_framework_jwt.serializers import User
from rest_framework import status, exceptions
class TokenAuthentication(BaseAuthentication):
model = None
def get_model(self):
return User
def authenticate(self, request):
auth = get_authorization_header(request).split()
if not auth or auth[0].lower() != b'token':
return None
if len(auth) == 1:
msg = 'Invalid token header. No credentials provided.'
raise exceptions.AuthenticationFailed(msg)
elif len(auth) > 2:
msg = 'Invalid token header'
raise exceptions.AuthenticationFailed(msg)
try:
token = auth[1]
if token == "null":
msg = 'Null token not allowed'
raise exceptions.AuthenticationFailed(msg)
except UnicodeError:
msg = 'Invalid token header. Token string should not contain invalid characters.'
raise exceptions.AuthenticationFailed(msg)
return self.authenticate_credentials(token)
def authenticate_credentials(self, token):
model = self.get_model()
payload = jwt.decode(token, settings.SECRET_KEY)
email = payload['email']
userid = payload['id']
msg = {'Error': "Token mismatch", 'status': "401"}
try:
user = User.objects.get(
email=email,
id=userid,
is_active=True
)
if not user.token['token'] == token:
raise exceptions.AuthenticationFailed(msg)
except jwt.ExpiredSignature or jwt.DecodeError or jwt.InvalidTokenError:
return HttpResponse({'Error': "Token is invalid"}, status="403")
except User.DoesNotExist:
return HttpResponse({'Error': "Internal server error"}, status="500")
return (user, token)
def authenticate_header(self, request):
return 'Token'