PylonsHQ.

Feb 5, 2009 6:49:19 PM

repoze.what authorization decorators for pylons

Authentication decorators.

@auth(not_anonymous()) uses pylons's abort() function when authorization fails.

@auth_render_error(not_anonymous()) renders misc.mako template and passes message as an extra variable.

authed_for(not_anonymous()) function returns True if authorization succeeds and error message when fails.

def auth(predicate, status=401):
    """ aborts with 401 status if authorization fails """

    @decorator
    def wrapper(f, *a, **kw):
        try:
            check_authorization(predicate, request.environ)
        except NotAuthorizedError:
            abort(status)
        return f(*a, **kw)

    return wrapper

def authed_for(predicate):
    """ return True if authorization succeedes """

    try:
        check_authorization(predicate, request.environ)
    except NotAuthorizedError, e:
        return e.message
    else:
        return True

def auth_render_error(predicate, template='/misc.mako'):
    """ when not authorized, render message passed to the predicates """

    @decorator
    def wrapper(f, *a, **kw):
        try:
            check_authorization(predicate, request.environ)
        except NotAuthorizedError, e:
            return render(template, extra_vars={'error': e.message})
        return f(*a, **kw)

    return wrapper

Comments (0)

You must login before you can comment.

Powered by Pylons - Contact Administrators