aboutsummaryrefslogtreecommitdiff
path: root/uploader/authorisation.py
blob: 71b42fa2b12d9de0a67c90af5a2cd0ebb59333fd (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
"""Authorisation utilities."""
from functools import wraps
from urllib.parse import urljoin

from flask import flash, redirect

from uploader import session
from uploader.oauth2.client import oauth2_client, authserver_uri

def require_login(function):
    """Check that the user is logged in before executing `func`."""
    @wraps(function)
    def __is_session_valid__(*args, **kwargs):
        """Check that the user is logged in and their token is valid."""
        def __clear_session__(_no_token):
            session.clear_session_info()
            flash("You need to be logged in.", "alert-danger")
            return redirect("/")

        def __with_token__(token):
            resp = oauth2_client().get(
                urljoin(authserver_uri(), "auth/user/"))
            userdetails = resp.json()
            if not userdetails.get("error"):
                return function(*args, **kwargs)
            return __clear_session__(token)
        return session.user_token().either(__clear_session__, __with_token__)
    return __is_session_valid__