aboutsummaryrefslogtreecommitdiff
path: root/gn2/wqflask/oauth2/checks.py
blob: 1d355ed8bcc33401663e08d9729fd9b1dccdf3af (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
"""Various checkers for OAuth2"""
from functools import wraps
from urllib.parse import urljoin

from authlib.integrations.requests_client import OAuth2Session
from flask import (
    flash, request, url_for, redirect, current_app, session as flask_session)

from . import session
from .client import authserver_uri, oauth2_clientid, oauth2_clientsecret

def user_logged_in():
    """Check whether the user has logged in."""
    suser = session.session_info()["user"]
    if suser["logged_in"]:
        if session.expired():
            session.clear_session_info()
            return False
        return suser["token"].is_right()
    return False

def require_oauth2(func):
    """Decorator for ensuring user is logged in."""
    @wraps(func)
    def __token_valid__(*args, **kwargs):
        """Check that the user is logged in and their token is valid."""
        config = current_app.config
        def __clear_session__(_no_token):
            session.clear_session_info()
            flask_session.pop("oauth2_token", None)
            flask_session.pop("user_details", None)
            flash("You need to be logged in.", "alert-warning")
            return redirect("/")

        def __with_token__(token):
            client = OAuth2Session(
                oauth2_clientid(), oauth2_clientsecret(), token=token)
            resp = client.get(
                urljoin(AUTH_SERVER_URL, "auth/user/"))
            user_details = resp.json()
            if not user_details.get("error", False):
                return func(*args, **kwargs)

            return clear_session_info(token)

        return session.user_token().either(__clear_session__, __with_token__)

    return __token_valid__