using has_secure_password

For authentication, we need to do following three:

So, we add has_secure_password to User model,

  has_secure_password

and it requires gem ‘bcrypt-ruby’ to the Gemfile,

  gem 'bcrypt-ruby'

$ bundle install

it makes some gibberish for us. and then we add another column (by convention, name) password_digest.

$ rails generate migration add_password_digest_to_users
  add_column :users, :password_digest, 'string'

$ rake db:migrate

When we set password attribute to user instance like,

> user = User.find 1
> user.password = "open_sesame"
> user.password_confirmation = "open_sesame"
> user.save

For information, actually has_secure_password has its validation in it – A password attribute value (and a password_confirmation value are) required to save the object. Or we can

  has_secure_password validations: false

do this and put validation on model ourselves.

However, and then, the password_digest of the user now with data. (By the way it would get different value even if password the same.) From here we need to know

> user.authenticate("not_matching") 
=> false
> user.authenticate("open_sesame")  # matching
=> < ... >  # user object

and use it for authentication (or “log-in”) feature. That’s it!

 
1
Kudos
 
1
Kudos

Now read this

How do you install ruby before 1.9.3?

How do you install ruby before 1.9.3? rbenv install --list rbenv install 1.9.2-p180 old version error. Need apple-gcc42, $ ls -l /usr/bin | grep gcc -rwxr-xr-x 1 root wheel 14224 Apr 8 14:45 gcc lrwxr-xr-x 1 root wheel 5 Apr 8 14:45... Continue →