-
Notifications
You must be signed in to change notification settings - Fork 52
/
Copy pathauthentication.py
33 lines (25 loc) · 1.12 KB
/
authentication.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
from rest_framework.authentication import BaseAuthentication, get_authorization_header
from rest_framework.exceptions import AuthenticationFailed
from .middleware import get_user
INVALID_TOKEN_MESSAGE = "Invalid JWT Token"
class ShopifyTokenAuthentication(BaseAuthentication):
keyword = "Bearer"
def authenticate(self, request):
auth = get_authorization_header(request).split()
if not auth or auth[0].lower() != self.keyword.lower().encode():
return None
if len(auth) == 1:
msg = "Invalid token header. No credentials provided."
raise AuthenticationFailed(msg)
elif len(auth) > 2:
msg = "Invalid token header. Token string should not contain spaces."
raise AuthenticationFailed(msg)
try:
token = auth[1].decode()
except UnicodeError:
msg = "Invalid token header. Token string should not contain invalid characters."
raise AuthenticationFailed(msg)
user = get_user(token)
if not user:
raise AuthenticationFailed(INVALID_TOKEN_MESSAGE)
return user, token