2012-03-01 107 views
0

我在我的config.ru中使用Basic Auth进行身份验证。在Auth Basic块中,我想从路径中获取ID,并检查用户是否有权查看路径。但是,我无法弄清楚如何访问路径。在config.ru中访问机架路由

use Rack::Auth::Basic do |username, password| 
    # access path here 
end 

任何想法?

回答

0

当您通过use使用推送Rack::Auth::Basic时,实际上是将其插入到请求处理链中。这将尝试授权所有的请求。要有选择地使用它,只有在某些路径上,您只需在相应的请求端点(操作)上执行auth。喜欢的东西 -

# helpers in ApplicationController 
def authorized? 
    @auth = Rack::Auth::Basic::Request.new(request.env) 
    @auth.provided? && @auth.basic? && @auth.credentials && @auth.credentials == ['username', 'password'] 
end 

def username(username) 
    @auth.credentials[0] 
end 

# action in PostsController 
def index 
if authorized?(params[:id]) && username == "admin" 
    # protected stuff 
else 
    render :text => "unauthorized" 
end 
end 

编号:Sinatra doc

尽管这种身份验证的可以处理做一个完整的用户账户和基于会话的方式要好得多。请在rails 3.1或devise中检出has_secure_password