using has_secure_password

For authentication, we need to do following three:

So, we add has_secure_password to User model,


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"

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!


Now read this

Authorization with Pundit

I want share my experience in the group from our Monday meetup yesterday. Let’s refresh the memory: “do authorization with pundit gem” – Homework here on github issue #12 We went to this page and bundle... Continue →