2013-11-20 82 views
1

我正在使用authenticate_or_request_with_http_digest在我的應用程序中進行簡單管理。如果管理員可以在登錄時看到對象的所有deleteedit鏈接,但對於常規用戶隱藏這些鏈接將會很好。authenticate_or_request_with_http_digest的Current_user方法 - Rails 4

該應用程序沒有用戶註冊的範圍或多個用戶如此設計或類似的認證平臺似乎矯枉過正在這種情況下。

我試圖在視圖中使用authenticate方法,就像使用current_user方法一樣。但是,它無限提示您登錄,這並不理想。

有沒有辦法複製流行的current_user方法來檢查會話是否已經創建並將其用作輔助方法?

application_controller.rb

helper_method :authenticate 

USERS = { "username" => "password", 
      "APP" => Digest::MD5.hexdigest(["APP", "realm", "password"].join(":"))} 

private 

def authenticate 
    authenticate_or_request_with_http_digest(CONFIG[:realm]) do |username| 
     USERS[username] 
    end 
    end 

在控制器使用

before_action :authenticate 

更新

感謝彼得·戈爾茨坦的回答,我能夠保存用戶名的身份驗證塊內成session[:admin]變量,並在current_user輔助方法中使用它。

+0

你有對應於用戶哈希的用戶模型可見?你如何確定用戶是否是管理員? –

+0

沒有用戶模型或表,代碼已從這裏複製:http://api.rubyonrails.org/classes/ActionController/HttpAuthentication/Digest.html。這是最簡單的身份驗證形式,如果用戶名和密碼正確,您將會登錄。 – dodgerogers747

+0

正確 - 但您的意思是管理員和非管理員之間存在區別。你如何根據用戶名和密碼來確定用戶是否是管理員? (注意:您複製的示例代碼沒有這樣的區別) –

回答

2

事情是這樣的:

def authenticate 
    current_user_name = nil 
    is_authenticated = authenticate_or_request_with_http_digest(CONFIG[:realm]) do |username| 
    current_user_name = username 
    USERS[username] 
    end 
    @current_user = current_user_name if is_authenticated 
    is_authenticated 
end 

def current_user 
    @current_user 
end 
helper_method :current_user 

應捕獲來自HTTP的用戶名消化請求,並使其在CURRENT_USER方法

相關問題