aboutsummaryrefslogtreecommitdiff
path: root/app/app_sessions.py
blob: 89521fba87c313a5ec2d19a2a09dc21c8e4203c3 (plain)
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
# UGE / L2 / Intro to relational databases / Python project prototype
# Author: Pacien TRAN-GIRARD
# Licence: EUPL-1.2

from os import environ
from functools import partial

from fastapi import Request, HTTPException, status
from starlette.middleware.sessions import SessionMiddleware


# Use a signed-cookie session manager.
# The default SameSite policy offers some protection against CSRF attacks.
cookie_key = environ['COOKIE_SECRET_KEY']
SessionManager = partial(SessionMiddleware, secret_key=cookie_key)


class UserSession:
    """
    Session decorator for managing user login sessions.
    """

    def __init__(self, request: Request):
        self._session = request.session

    def is_logged_in(self) -> bool:
        return 'user_id' in self._session

    def get_user_id(self) -> int:
        return self._session['user_id']

    def login(self, user_id: int):
        self._session['user_id'] = user_id

    def logout(self):
        self._session.pop('user_id', None)

    @classmethod
    def authenticated(cls, request: Request) -> 'UserSession':
        """
        Returns the authenticated user session or raises an HTTP Exception,
        dropping the request if the user is not logged in.
        """
        session = cls(request)
        if not session.is_logged_in():
            raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED)

        return session