2013-02-20 25 views
1

我可能忽略了簡單的事情,但我無法獲得Cherrypy SessionAuth的工作。cherrypy SessionAuth不工作?

使用調試並在cherrypy.session沒有用戶名,SessionAuth把這個日誌文件:

[20/Feb/2013:00:58:39] TOOLS.SESSAUTH No username, routing to login_screen with from_page 'http://localhost:8080/' 

麻煩的是它沒有路由的登錄屏幕。它將返回true給調用者並且調用者繼續執行。它還將cherrypy.serving.response.body設置爲呈現到登錄頁面的html代碼片段。但是我的調用函數對response.body一無所知。

我在做什麼錯?

下面是從root.py相關代碼:

class MySessionAuth(cptools.SessionAuth): 

    def check_username_and_password(self, username, password): 
     users = dict(foo="bar") 
     if username in users and password == users[username]: 
      return False 

    def on_check(self, username): 
     cherrypy.session['username'] = username 


def session_auth(**kwargs): 
    sa = MySessionAuth() 
    for k, v in kwargs.items(): 
     setattr(sa, k, v) 
    return sa.run() 

cherrypy.tools.protect = cherrypy._cptools.Tool('before_handler', session_auth) 


class Root: 
    @cherrypy.expose() 
    @cherrypy.tools.protect(debug=True) 
    def index(self): 
     tmpl = loader.load('index.html') 
     return tmpl.generate(flash = '',).render('html', doctype='html') 

回答

2

如果你想保護的密碼和整個應用程序而不只是某些資源可以爲check_username_and_password和在應用程序配置創建一個自定義功能有check_username_and_password指向它。 的配置行添加想這樣的事情

'tools.session_auth.check_username_and_password':check_username_and_password 

然後,只需使用已高於自定義check_username_and_password,它應該工作。

這裏是一個完整的例子,將保護所有的資源都在一個應用程序

import cherrypy 
from datetime import datetime 

user_dict={'peter':'password','joe':'pass1234','tom':'!Sm,23&$fiuD'} 
def check_user(username,password): 
    if user_dict.has_key(username): 
      if user_dict[username] == password: 
       return 
      else: 
       return 'incorrect password for user' 
    return 'user does not exist' 

class Root: 
    @cherrypy.expose 
    def index(self): 
      cherrypy.session.regenerate() 
      cherrypy.session['access_datetime'] = datetime.now() 
      return """Hello protected resource! <br \> 
datetime of access was %s 
<br /><a href="./logout">Logout</a>"""%cherrypy.session['access_datetime'] 


    @cherrypy.expose 
    def logout(self): 
      username = cherrypy.session['username'] 
      cherrypy.session.clear() 
      return """%s you have been logged out 
of the system at datetime %s"""%(username,datetime.now()) 

_cp_config={'/':{'tools.sessions.on':True, 
       'tools.sessions.storage_type':'file', 
       'tools.sessions.storage_path':'./', 
       'tools.sessions.timeout':60, 
       'tools.session_auth.on':True, 
       'tools.session_auth.check_username_and_password':check_user, 
       } 
      } 
cherrypy.config.update({'server.socket_host':'0.0.0.0', 
         'server.socket_port':8090}) 
cherrypy.quickstart(Root(),'/',config=_cp_config)