aboutsummaryrefslogtreecommitdiff
path: root/pyaggr3g470r/decorators.py
blob: a13dacac837ae2564d3aa0d4bf83f34976763aa9 (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
#! /usr/bin/env python
#-*- coding: utf-8 -*-

from threading import Thread
from functools import wraps

from flask import g, redirect, url_for, flash
from flask.ext.babel import gettext
from flask.ext.login import login_required

from pyaggr3g470r.models import Feed
from pyaggr3g470r.lib.exceptions import PyAggError


def async(f):
    """
    This decorator enables to launch a task (for examle sending an email or
    indexing the database) in background.
    This prevent the server to freeze.
    """
    def wrapper(*args, **kwargs):
        thr = Thread(target=f, args=args, kwargs=kwargs)
        thr.start()
    return wrapper

def feed_access_required(func):
    """
    This decorator enables to check if a user has access to a feed.
    The administrator of the platform is able to access to the feeds
    of a normal user.
    """
    @wraps(func)
    def decorated(*args, **kwargs):
        if kwargs.get('feed_id', None) is not None:
            feed = Feed.query.filter(Feed.id == kwargs.get('feed_id', None)).first()
            if feed is not None and (feed.subscriber.id == g.user.id or g.user.is_admin()):
                return func(*args, **kwargs)
            flash("This feed do not exist.", "danger")
            return redirect(url_for('home'))
        else:
            return func(*args, **kwargs)
    return decorated


def handle_pyagg_error(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except PyAggError, error:
            flash(gettext(error.default_message), 'warning')
            return redirect(url_for('home'))
    return wrapper


def pyagg_default_decorator(func):
    @login_required
    @handle_pyagg_error
    @wraps(func)
    def wrapper(*args, **kwargs):
        return func(*args, **kwargs)
    return wrapper
bgstack15