|
| 1 | +import hashlib |
| 2 | +from typing import Optional |
| 3 | + |
| 4 | +from fastapi import Request |
| 5 | +from fastapi import Response |
| 6 | + |
| 7 | +from infrastructure.num_convert import try_int |
| 8 | + |
| 9 | +auth_cookie_name = 'pypi_account' |
| 10 | + |
| 11 | + |
| 12 | +def set_auth(response: Response, user_id: int): |
| 13 | + hash_val = __hash_text(str(user_id)) |
| 14 | + val = "{}:{}".format(user_id, hash_val) |
| 15 | + response.set_cookie(auth_cookie_name, val, secure=False, httponly=True, samesite='Lax') |
| 16 | + |
| 17 | + |
| 18 | +def __hash_text(text: str) -> str: |
| 19 | + text = 'salty__' + text + '__text' |
| 20 | + return hashlib.sha512(text.encode('utf-8')).hexdigest() |
| 21 | + |
| 22 | + |
| 23 | +def get_user_id_via_auth_cookie(request: Request) -> Optional[int]: |
| 24 | + if auth_cookie_name not in request.cookies: |
| 25 | + return None |
| 26 | + |
| 27 | + val = request.cookies[auth_cookie_name] |
| 28 | + parts = val.split(':') |
| 29 | + if len(parts) != 2: |
| 30 | + return None |
| 31 | + |
| 32 | + user_id = parts[0] |
| 33 | + hash_val = parts[1] |
| 34 | + hash_val_check = __hash_text(user_id) |
| 35 | + if hash_val != hash_val_check: |
| 36 | + print("Warning: Hash mismatch, invalid cookie value") |
| 37 | + return None |
| 38 | + |
| 39 | + return try_int(user_id) |
| 40 | + |
| 41 | + |
| 42 | +def logout(response: Response): |
| 43 | + response.delete_cookie(auth_cookie_name) |
0 commit comments