Search code examples
pythonfalconframework

how to pass arguments to falcon.before hook?


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?


Solution

  • 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):
            ...