· 7 years ago · May 20, 2018, 09:06 PM
1class TokenAuthentication(BaseAuthentication):
2
3 model = None
4
5 def get_model(self):
6 return User
7
8 def authenticate(self, request):
9 auth = get_authorization_header(request).split()
10 if not auth or auth[0].lower() != b'token':
11 return None
12
13 if len(auth) == 1:
14 msg = 'Invalid token header. No credentials provided.'
15 raise exceptions.AuthenticationFailed(msg)
16 elif len(auth) > 2:
17 msg = 'Invalid token header'
18 raise exceptions.AuthenticationFailed(msg)
19
20 try:
21 token = auth[1]
22 if token=="null":
23 msg = 'Null token not allowed'
24 raise exceptions.AuthenticationFailed(msg)
25 except UnicodeError:
26 msg = 'Invalid token header. Token string should not contain invalid characters.'
27 raise exceptions.AuthenticationFailed(msg)
28
29 return self.authenticate_credentials(token)
30
31 def authenticate_credentials(self, token):
32 model = self.get_model()
33 payload = jwt.decode(token, "SECRET_KEY")
34 email = payload['email']
35 userid = payload['id']
36 msg = {'Error': "Token mismatch",'status' :"401"}
37 try:
38
39 user = User.objects.get(
40 email=email,
41 id=userid,
42 is_active=True
43 )
44
45 if not user.token['token'] == token:
46 raise exceptions.AuthenticationFailed(msg)
47
48 except jwt.ExpiredSignature or jwt.DecodeError or jwt.InvalidTokenError:
49 return HttpResponse({'Error': "Token is invalid"}, status="403")
50 except User.DoesNotExist:
51 return HttpResponse({'Error': "Internal server error"}, status="500")
52
53 return (user, token)
54
55 def authenticate_header(self, request):
56 return 'Token'