I summarized the has_secure_passsword method.
has_secure_password is a method that hash (encrypts) the password.
To use this method, you need to do the following two things.
-Add a gem called bcrypt
.
-Create a column called password_digest
in the database.
Define it in the model file as follows.
user.rb
class User < ApplicationRecord
~
~
~
has_secure_password
end
-You will be able to use two pairs of virtual attributes. (Password
and password_confirmation
)
-The autheticate
method can be used.
・ Password
attribute
Saved in the database. (Because it is a virtual attribute, it cannot be seen on the table)
-Password_confirmation
attribute
Password input is confirmed for virtual attributes that are not saved in the database.
This attribute is used to automatically add validation if both the password
and password_confirmation
attributes match.
Supplement
In the password_digest
attribute, put the hashed value of the value put in the password
attribute.
The authenticate
method is a method to check if the passwords match.
001:0> user = User.find_by(email: "example.com")
002:0> user.password_digest #Check the hash value of the password. Make sure it is hashed.
=> "$2a$10$YmQTuuDNOszvu5yi7auOC.F4G//FGhyQSWCpghqRWQWITUYlG3XVy"
003:0>user.authenticate("not_the_right_password") #Enter the wrong password
=> false
004:0>user.authenticate("foobar") #Enter the correct password
=> #<User id: 1, name: "example_user", email: "[email protected]",
created_at: "2014-07-25 02:58:28", updated_at: "2014-07-25 02:58:28",
password_digest: "$2a$10$YmQTuuDNOszvu5yi7auOC.F4G//FGhyQSWCpghqRWQW...">
005:0>!!user.authenticate("foobar") #To head"!!To get the logical value by adding "".
=> true
Recommended Posts