2014-06-08 79 views
0

我有一个CherryPy服务器,分配一些静态HTML/JS /等。文件到/ foosball,再加上一些JSON通过REST API到/。CherryPy访问限制与静态文件

import cherrypy 

config = { 
    'global': { 
     'server.socket_host': '0.0.0.0', 
     'server.socket_port': # my port here, 
     'tools.json_in.on': True 
    }, 
    '/foosball': { 
     'tools.staticdir.on': True, 
     'tools.staticdir.root': '/var/www/html', 
     'tools.staticdir.dir': 'foosball', 
     'tools.staticdir.index': 'index.html' 
    } 
} 

@cherrypy.popargs('player_id') 
class RESTClient_Player(object): 
    # stuff 

class RESTClient_Game(object): 
    # stuff 

class RESTClient: 
    players = RESTClient_Player() 
    games = RESTClient_Game() 

    @cherrypy.expose 
    def index(self): 
     http_method = getattr(self, cherrypy.request.method) 
     return (http_method)() 

cherrypy.quickstart(RESTClient(), '/', config) 

我也想保持这些页面由基本的访问限制方案保护的,所以我一直在研究the excellent tutorial CherryPy provides

问题是,该文档面向非静态页面进行身份验证,这种语句由def语句明确声明。我尝试过,并且未能将此文档适用于/ foosball中的文件,但没有成功。/foosball总是在没有任何认证请求的情况下加载。

我可以添加什么来给静态文件一些访问限制的能力?

谢谢!


编辑:我被指出对auth_tool。随着下面的配置块,我就能够锁定一个登录屏幕的REST API部分,但在/桌上足球的所有静态文件仍然公开访问:

def check_login_and_password(login, password): 
    cherrypy.log(login) 
    cherrypy.log(password) 

    return 

config = { 
    'global': { 
     'server.socket_host': '0.0.0.0', 
     'server.socket_port': # my port here, 
     'tools.json_in.on': True, 
     'tools.sessions.on': True, 
     'tools.session_auth.on': True, 
     'tools.session_auth.check_username_and_password': check_login_and_password 
    }, 
    '/foosball': { 
     'tools.staticdir.on': True, 
     'tools.staticdir.root': '/var/www/html', 
     'tools.staticdir.dir': 'foosball', 
     'tools.staticdir.index': 'index.html', 
     'tools.sessions.on': True, 
     'tools.session_auth.on': True, 
     'tools.session_auth.check_username_and_password': check_login_and_password 
    } 
} 
+0

尝试[session_auth(http://docs.cherrypy.org/en/latest/pkg/cherrypy.lib.html?highlight=session_auth#cherrypy.lib.cptools.session_auth)工具? – jwalker

+0

谢谢,我不知道这一点。请参阅上面的编辑以获得我的经验。 – spamguy

+0

这些文件必须来自浏览器缓存,请尝试Ctrl + Refresh。我刚刚尝试过,并且auth工具对我有用,但它在登录表单显示中将内容类型从图像更改为html并不够智能。希望它是可配置的。 – jwalker

回答

1

而不是在你的配置使用“staticdir” ,你可以在你的类中创建一个返回静态文件的函数。如果你这样做,你可以在你的函数中打包认证。

import cherrypy 
from cherrypy.lib.static import serve_file 
import os 

class Hello(object): 
    @cherrypy.expose 
    def index(self): 
     return "Hello World" 

    @cherrypy.expose 
    def static(self, page): 
     return serve_file(os.path.join(current_dir, 'static', page), content_type='text/html') 


if __name__ == '__main__': 
    current_dir = os.path.dirname(os.path.abspath(__file__)) 
    cherrypy.quickstart(Hello())