how to pass arguments to falcon.before hook?

1.7k views Asked by At

I need to authorize user based on some rols, so I need to:

class Things:
    @falcon.before(myfunc, 'can_delete_tag')
    @on_get(req, resp):
        ...

but it seems impossible... Any ideas?

2

There are 2 answers

1
Farshid Ashouri On BEST ANSWER

Using internal falcon hooks is impossible unless we patch the functionality of falcon. Because hooks in falcon do not accept any parameters at all. But a standard decorator can do that:

def Authorize(action):
    def request_checked(func):
        def _f(self, req, resp, *args, **kw):
            u = getUserInfoFromSession(req)
            if isAuthorizedTo(u.get('id'), action):
                return func(self, req, resp, *args, **kw)
            else:
                raise falcon.HTTPUnauthorized('Not Authorized', 'Permission Denied')
        return _f
    return request_checked

and now we can use it:

class Things:
    @Authorize('can_delete_tag')
    @on_get(req, resp):
        ...
2
Kiwi Scott On

Falcon 1.3 seems to have the same restriction! Heres a work-around

import falcon


class HasPermission(object):
    def __init__(self, role_name):
        self.role_name = role_name

    def validate_has_role(self, req, resp, resource, params):
        raise falcon.HTTPBadRequest('Bad request')

and to use it.....

class Things:
    @Authorize('can_delete_tag')
@on_get(req, resp):
    ...

write_access = HasPermission("WRITE").validate_has_role
read_access = HasPermission("READ").validate_has_role