forked from canada-ca/tracker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_json_web_token.py
More file actions
58 lines (38 loc) · 1.66 KB
/
test_json_web_token.py
File metadata and controls
58 lines (38 loc) · 1.66 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
49
50
51
52
53
54
55
56
57
58
import pytest
import jwt
from datetime import datetime as dt, timedelta
from json_web_token import tokenize
from os import environ
def test_that_it_generates_a_token():
token = tokenize(parameters={"user_id": 1}, secret="secret")
decoded = jwt.decode(token, "secret", algorithms=["HS256"])
exp, iat, parameters = decoded.values()
assert parameters.get("user_id") is 1
def test_tokens_expire_in_one_hour_by_default():
token = tokenize(parameters={"user_id": 1}, secret="secret")
decoded = jwt.decode(token, "secret", algorithms=["HS256"])
exp, iat, _ = decoded.values()
created = dt.fromtimestamp(iat)
expiry = dt.fromtimestamp(exp)
auth_duration_in_seconds = int((expiry - created).total_seconds())
assert auth_duration_in_seconds == 3600 # 1 hour
def test_accepts_an_iat_and_exp_argument_to_allow_custom_expiry_dates():
now = dt.utcnow()
token = tokenize(
parameters={"user_id": 1},
secret="secret",
iat=now,
exp=now + timedelta(seconds=100),
)
decoded = jwt.decode(token, "secret", algorithms=["HS256"])
exp, iat, _ = decoded.values()
created = dt.fromtimestamp(iat)
expiry = dt.fromtimestamp(exp)
auth_duration_in_seconds = int((expiry - created).total_seconds())
assert auth_duration_in_seconds == 100 # 1 day
def test_it_uses_a_secret_from_the_env_if_no_secret_arg_is_passed():
secret_from_the_environment = environ.get("SUPER_SECRET_SALT", "")
token = tokenize(parameters={"user_id": 1})
decoded = jwt.decode(token, secret_from_the_environment, algorithms=["HS256"])
_, _, parameters = decoded.values()
assert parameters.get("user_id") is 1