-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathauth.py
More file actions
83 lines (62 loc) · 2.11 KB
/
auth.py
File metadata and controls
83 lines (62 loc) · 2.11 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
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
""" Authentication and Crypto abstractions
This module provides a set of utilities to help with authentication and
crypto related tasks. The output of the various functions are meant to be
stored in databases or used for generating authenticated sessions.
The aim is to abstract these away from the models or routers, so that
they can be used in a variety of contexts.
These are also heavily inspired by the FastAPI documentation:
https://fastapi.tiangolo.com/tutorial/security/
"""
from datetime import datetime, timedelta
import bcrypt
import jwt
from ..settings import settings
def verify_password(
plain_password,
hashed_password
) -> bool:
""" Use the crypt context to verify the password
the str.encode is used to convert the string to bytes
"""
return bcrypt.checkpw(
str.encode(plain_password),
str.encode(hashed_password)
)
def hash_password(password) -> str:
""" Use the crypt context to hash the password
This is used by the setter in the User model to hash
the password when the handlers set the property.
the input string has to be an byte string
"""
encoded_password = bcrypt.hashpw(
str.encode(password),
bcrypt.gensalt()
)
# Return a string representation so that it can be stored
return encoded_password.decode()
def create_access_token(
subject: str,
fresh: bool = False
) -> str:
""" Creates a JWT token for the user
This is used by the authentication handler to create
a JWT token for the user to use for subsequent requests.
Args:
subject (str): The subject of the token, usually the email
fresh (bool, optional): Whether the token is fresh or not.
Defaults to False.
Returns:
str: The encoded JWT token
"""
delta = timedelta(seconds=settings.lifetime.token_jwt_access)
to_encode = {
"sub": subject,
"fresh": fresh,
"exp": datetime.utcnow() + delta
}
encoded_jwt = jwt.encode(
to_encode,
settings.jwt.secret_key.get_secret_value(),
algorithm=settings.jwt.algorithm
)
return encoded_jwt