2013-04-07 15 views
6

私は、RailsとDeviseを使ってユーザーの認証用にアプリケーションを開発しています。いくつかの変更についてのみパスワードを尋ねる方法があるのだろうかと思います。例えばDevise:特定の状況でのみパスワードを尋ねます

とき、私はパスワードを求められることがしたい:

  • はパスワード

を変更し、私は、ユーザーがなく、他のフィールドを編集して自由になりたいアカウントを削除任意のパスワード:

  • ユーザー名
  • アバター

だから、私はこの二つの方法の間で交換する方法をしたいと思います。これをどうすれば解決できますか?

EDIT:考案のドキュメントで

私はこれを発見し、それが正常に動作し、それだけで私はパスワードを入力すると、パスワードや電子メールを変更することができます:今

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

'update'メソッドはユーザを削除しないため、何も追加できません。ユーザ属性の更新のみです。あなたのコントローラの 'destroy'メソッドに同じ種類のものを追加したいかもしれません – ted

答えて

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 %> 

あなたのアクションがUserControllerにある状態は次のようなものになるだろう:による質問の編集に

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

パスワードを要求していないのですか? – Zippie

+0

@Zippie、 "この方法では、ログインしているかどうかを確認し、ログインページにリダイレクトしない場合は、" http://asciicasts.com/episodes/210-customizing-devise – ted

+0

Franが投稿しました。いくつかの変更についてのみパスワードを尋ねる方法があります。 – Zippie

0

少なくともバージョン3.5以降の工夫(中destroy_with_password方法があります。 2)。それはlib/devise/models/database_authenticatable.rbにあり、current_passwordが一致した場合には、レコードを破壊

destroy_with_password(current_password) 

によって呼び出され、それ以外の場合はfalseを返します。

関連する問題