import pylons
from decorator import decorator
from pylons.controllers.util import abort
from repoze.what.authorize import check_authorization, NotAuthorizedError
from repoze.what.predicates import Predicate
from pylons import request

import logging
log = logging.getLogger(__name__)

def require(predicate):
    """
    Make repoze.what verify that the predicate is met.

    :param predicate: A repoze.what predicate.
    :return: The decorator that checks authorization.

    """

    @decorator
    def check_auth(func, *args, **kwargs):
        environ = request.environ
        try:
            Predicate.check_authorization(predicate, environ)
        except NotAuthorizedError, reason:
            # TODO: We should warn the user
            # flash(reason, status='warning')
            abort(401)

        return func(*args, **kwargs)
    return check_auth

