Im having problems understanding the app logic to this password reset code i found below on the web.
- A user receives a an email with a
link with some reset code. - After clicking on this they go to
the action below called reset - The user is found in the db by
referencing the reset code. - The form to change password is shown
and the user enters the new password
in.
Heres where i get confused.
- When the form is submitted the action is called again.
- This time there will be no reset code in the params so no user will be found @user = nil
- This time its a post request so we enter that part of the logic.
My question is – How can this code ever be valid if @user = nil if @user.update_attributes(:password => params[:user][:password], :password_confirmation => params[:user][:password_confirmation])
# app/controllers/users_controller.rb
def reset
@user = User.find_by_reset_code(params[:reset_code]) unless params[:reset_code].nil?
if request.post?
if @user.update_attributes(:password => params[:user][:password], :password_confirmation => params[:user][:password_confirmation])
self.current_user = @user
@user.delete_reset_code
flash[:notice] = "Password reset successfully for #{@user.email}"
redirect_to root_url
else
render :action => :reset
end
end
end
<!-- app/views/users/reset.html.erb -->
<%= error_messages_for :user %>
<% form_for :user do |f| -%>
<p>
Pick a new password for <span><%= @user.email %></span>
</p>
<p>
<label for="password">Password</label><br />
<%= f.password_field :password %>
</p>
<p>
<label for="password">Confirm Password</label><br />
<%= f.password_field :password_confirmation %>
</p>
<p>
<%= submit_tag 'Reset' %>
</p>
<% end -%>
My answer would be that it is buggy code.
Firstly, the reset_code should be passed back to the controller via a hidden field on the form, or a parameter in the URL.
Secondly, if no reset_code is passed in (as shown), @user will be nil and you will get an AV. You’ll need to add a guard clause around the code:
Also, if it’s not included in the code already you need some way of expiring reset codes. On my system they expire after five days. You would need to add an extra field to your users table. Store the date the code is sent in there and include another guard clause that this is within the given time frame.
(Remember, just because you found it on the ‘net doesn’t mean it’s correct and bug free).