2013-04-07 43 views
6

我正在開發一個使用Rails和Devise進行用戶身份驗證的應用程序。我想知道是否有辦法只爲了一些更改而要求密碼。設計:僅在某些情況下要求密碼

舉例來說,我想詢問密碼時:

  • 刪除帳戶
  • 更改密碼

而且我希望用戶可以自由編輯等領域,而不任何密碼,如:

  • 名稱
  • 用戶名
  • 阿凡達

所以,我想某種程度上,這兩種方法之間切換。我該如何解決這個問題?

編輯:

在設計的文檔,我發現這一點,它工作得很好,只允許更改密碼,電子郵件,如果我輸入密碼:

def update 
    @user = User.find(current_user.id) 

    successfully_updated = if needs_password?(@user, params) 
     @user.update_with_password(params[:user]) 
    else 
     # remove the virtual current_password attribute update_without_password 
     # doesn't know how to ignore it 
     params[:user].delete(:current_password) 
     @user.update_without_password(params[:user]) 
    end 

    if successfully_updated 
     set_flash_message :notice, :updated 
     # Sign in the user bypassing validation in case his password changed 
     sign_in @user, :bypass => true 
     redirect_to after_update_path_for(@user) 
    else 
     render "edit" 
    end 

end 

private 

# check if we need password to update user data 
# ie if password or email was changed 
# extend this as needed 
def needs_password?(user, params) 
    user.email != params[:user][:email] || 
    !params[:user][:password].blank? 
    #HERE 
end 

現在,我能放什麼#HERE到當我刪除帳戶時還需要密碼?

+0

您不能添加任何'#HERE',因爲'update'方法不會刪除用戶,它只會更新用戶屬性。你可能想要添加相同類型的東西到你的控制器 – ted 2013-04-07 20:51:25

回答

0

您可以創建一個form_tag重定向到您的控制器中的操作。

<%= form_tag url_for(:controller => :users, :action => :destroy), :method => :get do %> 
    <%= label_tag(:password, "Enter password before deleting") %> 
    <%= password_field_tag :password %> 
    <%= submit_tag "Delete User With Confirmation" %> 
<% end %> 

在UsersController的行動將是這樣的:

def destroy 
    if current_user.authenticate(params[:password]) 
     #do something 
    else 
     #do something 
    end 
end 
3

由於問題編輯:

def destroy 
    if current_user.valid_password?(params[:user][:password]) 
    current_user.destroy 
    else 
    render "destroy" # or what ever 
    end 
end 
+0

中的'destroy'方法,它不要求輸入密碼,是嗎? – Zippie 2013-04-07 20:21:17

+0

@ Zippie,「這種方法可以確保用戶登錄,如果沒有將他們重定向到登錄頁面,」來源:http://asciicasts.com/episodes/210-customizing-devise – ted 2013-04-07 20:27:54

+0

Fran發表:「我想知道是否有一種方法只需要對密碼進行一些更改。「 – Zippie 2013-04-07 20:28:40

0

有一個在設計一種destroy_with_password方法(因爲3.5版本至少。 2)。它是在lib/devise/models/database_authenticatable.rb,由

destroy_with_password(current_password) 

稱爲它破壞了記錄,如果current_password相匹配,否則,返回假。

相關問題