Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable the has_secure_password password_confirmation check in Rails 4

I'm creating a basic Ruby on Rails 4 project that allows user to create accounts, login, etc... I'm using the built in has_secure_password to manage the password. I don't want users to have to enter their password twice (i.e. require a password_confirmation input form field and corresponding model attribute). So, I'm looking for a way to turn the password_confirmation check/requirement off.

I found this answer that provides a potential solution, but the original question is different enough that I want to verify it separately. It recommends updating the user model to add the following:

class User < ActiveRecord::Base

  # ...

  has_secure_password validations: false
  validates :password, presence: true, length: { minimum: 6 }

end

This seems to work and allows my RSpec tests to pass. My two part question is:

  1. Are there any negative consequences or security problems with this approach?
  2. Are there alternate ways to turn off password_confirmation that are safer or more inline with "The Ruby Way"?
like image 460
Alan W. Smith Avatar asked Oct 26 '13 01:10

Alan W. Smith


1 Answers

ActiveModel::SecurePassword has an options parameter to which you can specify not to perform validations.

has_secure_password validations: false

Then just make sure you perform a validation on your password field manually.

validates_presence_of :password, on: :create

Optionally the only other thing missing is to raise an error if the password_digest is somehow blank. I don't know how that could happen.

before_create { raise "Password digest missing on new record" if password_digest.blank? }

This seems to me resolves the issue as cleanly as possible.

like image 198
kequc Avatar answered Nov 22 '22 14:11

kequc