Writing a CherryPy Decorator for Authorization

I have a cherry application and some of the views that I want to run, only allowing certain users to view them and send to someone else on the required authorization page.

Is there any way to do this with a special decorator? I think that would be the most elegant option.

Here is a basic example of what I want to do:

class MyApp: @authorization_required def view_page1(self,appID): ... do some stuff ... return html def authorization_required(func): #what do I put here? 

Can the authorization_required function also accept parameters like allow_group1, allow_group2 when called as a decorator? Or do I need a separate decorator for each group?

+6
python cherrypy decorator authorization permissions
source share
2 answers

Well, in this case, your decorator will look something like this:

 # without any parameters def authentication_required(f): @functools.wraps(f) def _authentication_required(*args, **kwargs): # Do you login stuff here return f(*args, **kwargs) return _authentication_required # With parameters def authentication_required(*allowed_groups): def _authentication_required(f): @functools.wraps(f) def __authentication_required(*args, **kwargs): # Do you login stuff here return f(*args, **kwargs) return __authentication_required return _authentication_required 
+4
source share

You really don't want to write custom decorators for CherryPy. Instead, you want to write a new tool:

 def myauth(allowed_groups=None, debug=False): # Do your auth here... authlib.auth(...) cherrypy.tools.myauth = cherrypy.Tool("on_start_resource", myauth) 

See http://docs.cherrypy.org/en/latest/extend.html#tools for more details. This has several advantages over writing a custom decorator:

  • You get the decorator for free from the Tool: @cherrypy.tools.myauth(allowed_groups=['me']) , and he already knows how not to clobber cherrypy.exposed on the same function.
  • You can use the Tools for each handler (with a decorator), the controller tree (via _cp_config ), and for each URI tree (in configuration files or dicts). You can even mix them and provide a basic function through decorators, and then override their behavior in the configuration files.
  • If the configuration file disables your function, you do not pay a fine for executing a call to the decorator function to ensure that it is disabled.
  • You do not forget to add "debug" arg, like all built-in tools .;)
  • Your function may work earlier (or later, if necessary) than a custom decorator by selecting a different β€œpoint”.
  • If necessary, your function can work with multiple capture points.
+13
source share

All Articles