diff options
Diffstat (limited to 'app/app_sessions.py')
-rw-r--r-- | app/app_sessions.py | 48 |
1 files changed, 48 insertions, 0 deletions
diff --git a/app/app_sessions.py b/app/app_sessions.py new file mode 100644 index 0000000..89521fb --- /dev/null +++ b/app/app_sessions.py | |||
@@ -0,0 +1,48 @@ | |||
1 | # UGE / L2 / Intro to relational databases / Python project prototype | ||
2 | # Author: Pacien TRAN-GIRARD | ||
3 | # Licence: EUPL-1.2 | ||
4 | |||
5 | from os import environ | ||
6 | from functools import partial | ||
7 | |||
8 | from fastapi import Request, HTTPException, status | ||
9 | from starlette.middleware.sessions import SessionMiddleware | ||
10 | |||
11 | |||
12 | # Use a signed-cookie session manager. | ||
13 | # The default SameSite policy offers some protection against CSRF attacks. | ||
14 | cookie_key = environ['COOKIE_SECRET_KEY'] | ||
15 | SessionManager = partial(SessionMiddleware, secret_key=cookie_key) | ||
16 | |||
17 | |||
18 | class UserSession: | ||
19 | """ | ||
20 | Session decorator for managing user login sessions. | ||
21 | """ | ||
22 | |||
23 | def __init__(self, request: Request): | ||
24 | self._session = request.session | ||
25 | |||
26 | def is_logged_in(self) -> bool: | ||
27 | return 'user_id' in self._session | ||
28 | |||
29 | def get_user_id(self) -> int: | ||
30 | return self._session['user_id'] | ||
31 | |||
32 | def login(self, user_id: int): | ||
33 | self._session['user_id'] = user_id | ||
34 | |||
35 | def logout(self): | ||
36 | self._session.pop('user_id', None) | ||
37 | |||
38 | @classmethod | ||
39 | def authenticated(cls, request: Request) -> 'UserSession': | ||
40 | """ | ||
41 | Returns the authenticated user session or raises an HTTP Exception, | ||
42 | dropping the request if the user is not logged in. | ||
43 | """ | ||
44 | session = cls(request) | ||
45 | if not session.is_logged_in(): | ||
46 | raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED) | ||
47 | |||
48 | return session | ||