I have a cherrypy application and on some of the views I want to start only allowing certain users to view them, and sending anyone else to an authorization required page.
Is there a way I can do this with a custom decorator? I think that would be the most elegant option.
Here's 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?
Also can the authorization_required function when called as a decorator accept parameters like allow_group1, allow_group2? Or do I need a separate decorator for each group?
You really don't want to be writing 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 discussion. This has several benefits over writing a custom decorator:
@cherrypy.tools.myauth(allowed_groups=['me'])
, and it already knows how to not clobber cherrypy.exposed on the same function._cp_config
) or per-URI-tree (in config files or dicts). You can even mix them and provide a base feature via decorators and then override their behavior in config files.Ok, in that case your decorator would 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With