CherryPy Custom Tool for user authentication
I'm trying to set up a simple way of decorating methods in my CherryPy controller classes so that a user is redirected to the login page if they haven't authenticated yet. I was going to do a basic Python decorator, but an answer here suggested I use a CherryPy Custom Tool instead. So I'm trying to do that, but I can't get it to work. Here's what I have:
def authenticate():
user = cherrypy.session.get('user', None)
if not user:
raise cherrypy.HTTPRedirect('/?errMsg=Please%20log%20in%20first')
cherrypy.tools.authenticate = cherrypy.Tool('on_start_resource', authenticate)
The /home
page is a page that should be restricted to authenticated users, so I have this:
@cherrypy.expose
@cherrypy.tools.authenticate
def home(self, **kwargs):
tmpl = TemplateDir.get_template('home.mako')
return tmpl.render()
However, I get this error when I try to start my web site:
Traceback (most recent call last):
File ".\example.py", line 3, in <module>
from controller.main import Root
File "C:\...\controller\main.py", line 9, in <module>
class Root(BaseModule):
File "C:\...\controller\main.py", line 19, in Root
@cherrypy.tools.authenticate
File "C:\Python26\lib\site-packages\cherrypy\_cptools.py", line 119, in
__call__ % self._name)
TypeError: The 'authenticate' Tool does not accept positional arguments; you must
use keyword arguments.
Edit: okay, if I change my use of the custom tool to have parentheses, I get a different error.
@cherrypy.expose
@cherrypy.tools.auth开发者_StackOverflow中文版enticate() # Magic parentheses...
def home(self, **kwargs):
...
Now I get:
Traceback (most recent call last):
File "C:\Python26\lib\site-packages\cherrypy\_cprequest.py", line 625, in respond
self.hooks.run('on_start_resource')
File "C:\Python26\lib\site-packages\cherrypy\_cprequest.py", line 97, in run
hook()
File "C:\Python26\lib\site-packages\cherrypy\_cprequest.py", line 57, in __call__
return self.callback(**self.kwargs)
File ".\example.py", line 40, in authenticate
user = cherrypy.session.get('user', None)
AttributeError: 'module' object has no attribute 'session'
Edit: I have sessions turned on:
cherrypy.tools.sessions.storage_type = 'file'
cherrypy.tools.sessions.storage_path = r'%s\sessions' % curDir
cherrypy.tools.sessions.timeout = 60
cherrypy.tree.mount(Root(), "/", config={
'/static': {
'tools.staticdir.on':True,
'tools.staticdir.dir':r'%s\static' % curDir,
},
'/': {
'tools.sessions.on':True,
}
})
When I first load the page with my custom tool decorator on the web method, I get this error:
AttributeError: 'module' object has no attribute 'session'
Then when I reload the page, I get this error:
AttributeError: '_Serving' object has no attribute 'session'
Edit: even trying this much in my controller class, I still get the 'module object has no attribute session' error:
class Root(BaseModule):
_cp_config = {'tools.sessions.on': True}
sess = cherrypy.session # Error here
...
I was using the wrong hook. Changing:
cherrypy.tools.authenticate = cherrypy.Tool('on_start_resource', authenticate)
To:
cherrypy.tools.authenticate = cherrypy.Tool('before_handler', authenticate)
Fixed the problem. Apparently my authenticate
method was getting called before sessions had been turned on, so it couldn't access cherrypy.session
. I didn't need any session-turn-on stuff in my controllers; all that was necessary was the following in my server-start script:
def authenticate():
...
cherrypy.tools.authenticate = cherrypy.Tool('before_handler', authenticate)
cherrypy.tree.mount(Root(), "/", config={
"/": {
'tools.sessions.on':True,
'tools.sessions.storage_type':'file',
'tools.sessions.storage_path':r'%s\sessions' % curDir,
'tools.sessions.timeout':60
}, ...
})
Then, in my controller on a restricted method:
@cherrypy.expose
@cherrypy.tools.authenticate()
def home(self, **kwargs):
...
Most likely sessions aren't enabled. There's an example config file on the session wiki page, or have a look at tutorial #7.
精彩评论