Currently my users need to enter their password in order to change their email address or password, but can delete their account without entering it. I am not sure how to require this.
So far I have:
Users controller:
def destroy
@user = User.find(current_user.id)
@user.destroy_with_password(user_params)
if @user.destroy
redirect_to root_url, notice: "User deleted."
else
redirect_to users_url
flash[:notice] = "Couldn't delete"
end
end
def user_params
params.require(:user).permit(:username, :email, :password,
:password_confirmation, :current_password, :avatar, etc....etc.... )
end
A form:
<%= simple_form_for(@user, :method => :delete) do |f| %>
<%= f.input :current_password, autocomplete: "off" %>
<%= f.button :submit %>
<% end %>
Here the user deletes even if no password is inputted. The delete request is being processed by the correct controller action ;
Processing by UsersController#destroy as HTML
Processing by UsersController#destroy as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"bla bla bla", "user"=>{"current_password"=>"[FILTERED]"}, "commit"=>"Update User", "locale"=>"en", "id"=>"ce2dc2edc"}
SQL (0.1ms) DELETE FROM "users" WHERE "users"."id" = $1 [["id", 15]]
How can I require the user's password in order to delete the account?
You're calling Devise's destroy_with_password
and then calling ActiveRecord's destroy
. You only need to call destroy_with_password
. Code should read as follows:
def destroy
@user = User.find(current_user.id)
if @user.destroy_with_password(user_params)
# if @user.destroy # <== remove me, don't need to destroy twice!
redirect_to root_url, notice: "User deleted."
else
redirect_to users_url
flash[:notice] = "Couldn't delete"
end
end
destroy_with_password
is going to return a truthy value.