We are moving from Devise to a more streamlined authentication process. If I can solve the following problem, I think I can get the rest of the authentication process working.
If one of our clients looses a password, they can submit their user ID and we will send them an email with a new password. The password that is sent in the email is not being saved in our system.
Gemfile:
gem 'bcrypt-ruby', '3.1.2'
Database Schema:
create_table "users", force: :cascade do |t|
...
t.string "username", limit: 255, null: false
t.string "password_digest", limit: 255
...
end
User model:
has_secure_password
...
attr_accessible ... :username, :password_digest, :password, :password_confirmation,...
...
def set_password(len = 12)
chars = ("a".."z").to_a + ("A".."Z").to_a + ("0".."9").to_a
newpass = ""
1.upto(len) { |i| newpass << chars[rand(chars.size-1)] }
self.password = self.password_confirmation = newpass
end
users_controller:
def send_new_password
@user = User.find_by_username(params[:username])
pw = @user.set_password
@user.save
UserMailer.new_password(@user).deliver_now
redirect_to sign_in_path
end
...
def user_params
params.require(:user).permit(... :username, :password_digest, :password, :password_confirmation,... )
end
I get invalid hash on this line: 'self.password = newpass'. If I change it to 'self.password_digest = newpass' then all proceeds but checking in the rails console 'puts u.password_digest' produces '=> nil'.
RESULT: We changed approach. No longer sending passwords in emails.
This is probably not the answer you want, but sending passwords to the user is bad practice. Any one telling you otherwise is wrong.
The devise gem has a module dedicated to resetting passwords, which involves email a link for users to recover & set their own password: https://www.rubydoc.info/github/heartcombo/devise/main/Devise/Models/Recoverable