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

레일스로 코딩 배우기

나는 루비가 코딩을 배우기에 좋은 출발점이라고 생각한다 Learn To Program 이라는 책을 읽어보라 https://pine.fm/LearnToProgram/ 물론 어느 programming language 로 시작하든지 코딩을 배우는 것은 인생에서 매우 중요하다고 생각한다 그리고 루비를 배우기에는 레일스가 좋은 출발점이라고 생각한다 지금 시작해보자 rails new app_name cd app_name 레일스의... Continue →