-
Notifications
You must be signed in to change notification settings - Fork 58
/
Copy pathtest_backend.py
92 lines (67 loc) · 2.67 KB
/
test_backend.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
import pytest
from django.conf import settings
from django.contrib.auth import get_user_model
from django.test import Client
from rest_framework import status
from rest_framework.exceptions import AuthenticationFailed
from utils import create_jwt_token
from django_cognito_jwt import backend
USER_MODEL = get_user_model()
def test_authenticate_no_token(rf):
request = rf.get("/")
auth = backend.JSONWebTokenAuthentication()
assert auth.authenticate(request) is None
def test_authenticate_valid(
rf, monkeypatch, cognito_well_known_keys, jwk_private_key_one
):
token = create_jwt_token(
jwk_private_key_one,
{
"iss": "https://cognito-idp.eu-central-1.amazonaws.com/bla",
"aud": settings.COGNITO_AUDIENCE,
"sub": "username",
},
)
def func(payload):
return USER_MODEL(username=payload["sub"])
monkeypatch.setattr(
USER_MODEL.objects, "get_or_create_for_cognito", func, raising=False
)
request = rf.get("/", HTTP_AUTHORIZATION=b"bearer %s" % token.encode("utf8"))
auth = backend.JSONWebTokenAuthentication()
user, auth_token = auth.authenticate(request)
assert user
assert user.username == "username"
assert auth_token == token.encode("utf8")
def test_authenticate_invalid(rf, cognito_well_known_keys, jwk_private_key_two):
token = create_jwt_token(
jwk_private_key_two,
{
"iss": "https://cognito-idp.eu-central-1.amazonaws.com/bla",
"aud": settings.COGNITO_AUDIENCE,
"sub": "username",
},
)
request = rf.get("/", HTTP_AUTHORIZATION=b"bearer %s" % token.encode("utf8"))
auth = backend.JSONWebTokenAuthentication()
with pytest.raises(AuthenticationFailed):
auth.authenticate(request)
def test_authenticate_error_segments(rf):
request = rf.get("/", HTTP_AUTHORIZATION=b"bearer randomiets")
auth = backend.JSONWebTokenAuthentication()
with pytest.raises(AuthenticationFailed):
auth.authenticate(request)
def test_authenticate_error_invalid_header(rf):
request = rf.get("/", HTTP_AUTHORIZATION=b"bearer")
auth = backend.JSONWebTokenAuthentication()
with pytest.raises(AuthenticationFailed):
auth.authenticate(request)
def test_authenticate_error_spaces(rf):
request = rf.get("/", HTTP_AUTHORIZATION=b"bearer random iets")
auth = backend.JSONWebTokenAuthentication()
with pytest.raises(AuthenticationFailed):
auth.authenticate(request)
def test_authenticate_error_response_code():
client = Client()
resp = client.get("/", HTTP_AUTHORIZATION=b"bearer random iets")
assert resp.status_code == status.HTTP_401_UNAUTHORIZED