summaryrefslogtreecommitdiffstats
path: root/bitvend/auth.py
blob: 5ad9154180b1614f071d33c958507b19d5852410 (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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import requests
import functools
import time
from flask import session, flash, redirect, request, current_app, abort
from flask_login import login_user, LoginManager, logout_user, current_user
from flask_login.signals import user_logged_out
from bitvend.models import User, db
from sqlalchemy import func


login_manager = LoginManager()
login_manager.refresh_view = "bitvend.login"
login_manager.needs_refresh_message = (
    u"To protect your account, please reauthenticate to access this page."
)
login_manager.needs_refresh_message_category = "info"

@login_manager.user_loader
def load_user(user_id):
    return User.find(user_id)

def try_login(username, password):
    resp = requests.post('https://auth.hackerspace.pl/', data={
        'login': username,
        'password': password
        })

    if resp.status_code == 200:
        u = User.find(username)

        if not u:
            u = User(uid=username)
            db.session.add(u)
            db.session.commit()

        login_user(u, remember=True)

        return True

    return False


def cap_check(capability, user=None):
    if not current_user.is_authenticated:
        return False

    user = user or current_user.get_id()

    cache_key = '{}-{}'.format(user, capability)
    cached_cap = session.get('_caps', {}).get(cache_key, (False, 0))

    if cached_cap[1] > time.time():
        return cached_cap[0]

    allowed = requests.get(
        'https://capacifier.hackerspace.pl/%s/%s' % (capability, user)
        ).status_code == 200

    if '_caps' not in session:
        session['_caps'] = {}

    session['_caps'][cache_key] = \
        (allowed, time.time() + current_app.config.get('CAP_TTL', 3600))

    return allowed


@user_logged_out.connect
def caps_cleanup(app, user):
    # Cleanup caps cache
    if '_caps' in session:
        session.pop('_caps')


def cap_required(capability):
    '''Checks if user has desired capacifier capability'''

    def inner(func):
        @functools.wraps(func)
        def wrapped(*args, **kwargs):
            if not cap_check(capability):
                abort(403)

            return func(*args, **kwargs)

        return wrapped
    return inner