2012-03-01 61 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