Skip to content

Instantly share code, notes, and snippets.

@amitpatelx
Last active December 25, 2015 01:59
Show Gist options
  • Save amitpatelx/6899837 to your computer and use it in GitHub Desktop.
Save amitpatelx/6899837 to your computer and use it in GitHub Desktop.
Change Password when user logged in. Assumption : Rails + Devise integrated
%h3= t('profile.change_password')
.row-fluid
.span12
.full-graph
.padded
= form_for @user, url: save_password_path, html: {class: 'form-horizontal'} do |f|
.row-fluid
.control-group
%label.control-label Current Password
.controls
= password_field_tag 'user[current_password]'
.control-group
%label.control-label New Password
.controls
= f.password_field :password
.control-group
%label.control-label= Confirm Password
.controls
= f.password_field :password_confirmation
.row-fluid
.span11.offset1.profile-actions
= f.submit t('actions.save'), disable_with: t('actions.saving'), class: 'btn btn-primary'
class ProfileController < ApplicationController
def update
user = params[:user]
#http://stackoverflow.com/a/4370106/517483
unless @user.valid_password?(user[:current_password])
flash[:alert] = 'Current password doesn't match. Please try again.'
render 'edit'
return
end
password = user[:password]
password_confirmation = user[:password_confirmation]
params[:user].delete(:current_password) #to avoid mass assign security error
unless passwords_match?(user)
flash[:alert] = 'New assword doesn't match with confirm password'
render 'edit'
return
end
if @user.update_attributes(params[:user])
# Sign in the user bypassing validation in case his password changed
sign_in(@user, :bypass => true)
flash[:notice] = t('devise.passwords.updated_not_active')
redirect_to profile_url
else
flash[:alert] = 'Something went wrong while updating password. Please try again.'
render 'change_password'
end
# required for settings form to submit when password is left blank
if params[:user][:password].blank?
params[:user].delete("password")
params[:user].delete("password_confirmation")
end
end
private
def passwords_match?(user)
return false if (user[:password].empty? || user[:password_confirmation].empty?)
user[:password] == user[:password_confirmation]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment