6

ユーザーの認証に Rails と Devise を使用してアプリを開発しています。一部の変更のみパスワードを尋ねる方法があるのだろうか。

たとえば、次の場合にパスワードを尋ねられるようにします。

  • アカウントの削除
  • パスワードの変更

また、ユーザーがパスワードなしで他のフィールドを自由に編集できるようにしたい:

  • 名前
  • ユーザー名
  • アバター

したがって、この 2 つの方法を切り替える方法が必要です。どうすればこれを解決できますか?

編集:

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では、アカウントを削除するときにパスワードも要求するには、何を入力すればよいでしょうか?

4

3 に答える 3

3

質問の編集により:

def destroy
  if current_user.valid_password?(params[:user][:password])
    current_user.destroy
  else 
    render "destroy" # or what ever
  end
end
于 2013-04-07T20:19:11.530 に答える
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
于 2013-04-07T20:10:02.130 に答える