File size: 4,332 Bytes
e53c2d7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
from app.backend.models.users import User, add_new_user, find_user_by_email, find_user_by_access_string, update_user
from bcrypt import gensalt, hashpw, checkpw
from app.settings import very_secret_pepper, jwt_algorithm, max_cookie_lifetime
from fastapi import HTTPException
import jwt
from datetime import datetime, timedelta
from fastapi import Response, Request
from secrets import token_urlsafe
import hmac
import hashlib

# A vot nado bilo izuchat kak web dev rabotaet

'''
Creates a jwt token by access string

Param:
access_string - randomly (safe methods) generated string (by default - 16 len) 
expires_delta - time in seconds, defines a token lifetime

Returns:
string with 4 sections (valid jwt token)
'''
def create_access_token(access_string: str, expires_delta: timedelta = timedelta(seconds=max_cookie_lifetime)) -> str:
    token_payload = {
        "access_string": access_string,
    }

    token_payload.update({"exp": datetime.now() + expires_delta})
    encoded_jwt: str = jwt.encode(token_payload, very_secret_pepper, algorithm=jwt_algorithm)

    return encoded_jwt
        

'''
Safely creates random string of 16 chars
'''
def create_access_string() -> str:
    return token_urlsafe(16)


'''
Hashes access string using hmac and sha256

We can not use the same methods as we do to save password
since we need to know a salt to get similar hash, but since
we put a raw string (non-hashed) we won't be able to guess
salt
'''
def hash_access_string(string: str) -> str:
    return hmac.new(
        key=very_secret_pepper.encode("utf-8"),
        msg=string.encode("utf-8"),
        digestmod=hashlib.sha256
    ).hexdigest()


'''
Creates a new user and sets a cookie with jwt token

Params:
response - needed to set a cookie
...

Returns:
Dict to send a response in JSON 
'''
def create_user(response: Response, email: str, password: str) -> dict:
    user: User = find_user_by_email(email=email)
    if user is not None:
        return HTTPException(418, "The user with similar email already exists")
    
    salt: bytes = gensalt(rounds=16)
    password_hashed: str = hashpw(password.encode("utf-8"), salt).decode("utf-8")
    
    access_string: str = create_access_string()
    access_string_hashed: str = hash_access_string(string=access_string)

    add_new_user(email=email, password_hash=password_hashed, access_string_hash=access_string_hashed)

    access_token: str = create_access_token(access_string=access_string)
    response.set_cookie(key="access_token", value=access_token, path='/', max_age=max_cookie_lifetime, httponly=True)

    return {"status": "ok"}



'''
Finds user by email. If user is found, sets a cookie with token
'''
def authenticate_user(response: Response, email: str, password: str) -> dict:
    user: User = find_user_by_email(email=email)

    if not user:
        raise HTTPException(418, "User does not exists")

    if not checkpw(password.encode('utf-8'), user.password_hash.encode('utf-8')):
        raise HTTPException(418, "Wrong credentials")

    access_string: str = create_access_string()
    access_string_hashed: str = hash_access_string(string=access_string)

    update_user(user, access_string_hash=access_string_hashed)
    
    access_token = create_access_token(access_string)
    response.set_cookie(key="access_token", value=access_token, path='/', max_age=max_cookie_lifetime, httponly=True)

    return {"status": "ok"}


'''
Get user from token stored in cookies
'''
def get_current_user(request: Request) -> User | None:
    token: str | None = request.cookies.get("access_token")
    if not token:
        return None
    
    access_string = jwt.decode(
            jwt=bytes(token, encoding='utf-8'),
            key=very_secret_pepper,
            algorithms=[jwt_algorithm]
        ).get('access_string')

    user = find_user_by_access_string(hash_access_string(access_string))
    if not user:
        return None
    
    return user


'''
Checks if cookie with access token is present
'''
def check_cookie(request: Request) -> dict:
    result = {"token": "No token is present"}
    token = request.cookies.get("access_token")
    if token:
        result["token"] = token
    return result


def clear_cookie(response: Response) -> dict:
    response.set_cookie(key="access_token", value="", httponly=True)
    return {"status": "ok"}