-
Notifications
You must be signed in to change notification settings - Fork 170
Expand file tree
/
Copy pathauthentication.py
More file actions
48 lines (38 loc) · 1.4 KB
/
authentication.py
File metadata and controls
48 lines (38 loc) · 1.4 KB
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
from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed
from users.models import User
AUTHORIZATION_HEADER = "Authorization"
API_KEY_HEADER = "X-API-Key"
class BearerAuthentication(BaseAuthentication):
"""Bearer Authentication."""
keyword = "Bearer"
header_name = AUTHORIZATION_HEADER
def authenticate(self, request):
"""Authenticate the user with Bearer token."""
auth = request.headers.get(self.header_name)
if not auth:
return None
parts = auth.split()
if len(parts) != 2 or parts[0] != self.keyword: # noqa: PLR2004
return None
token = parts[1]
try:
user = User.objects.get(token=token)
except User.DoesNotExist:
msg = "Invalid token"
raise AuthenticationFailed(msg) from None
return (user, None)
class APIKeyAuthentication(BaseAuthentication):
"""API Key Authentication."""
header_name = API_KEY_HEADER
def authenticate(self, request):
"""Authenticate the user with API Key."""
auth = request.headers.get(self.header_name)
if not auth:
return None
try:
user = User.objects.get(token=auth)
except User.DoesNotExist:
msg = "Invalid token"
raise AuthenticationFailed(msg) from None
return (user, None)