The guest login function has been added by referring to the following article.
How to implement easy login / guest login function (for portfolio)
I recommend this article because it is very helpful and easy to understand!
So, as for the main subject of this article, in the case of my portfolio site, a validation function was added with a password to enhance security, so if I implemented it as it is in the above article, an error occurred, so I have summarized the correspondence. I would like to come.
The content of the error seems to be that the generated password was a character string outside the regular expression.
logs/development.log
ActiveRecord::RecordInvalid (Validation failed:The password must be at least 6 characters long and must contain one uppercase letter, one lowercase letter, one number, and one special character.):
app/models/user.rb:41:in `guest'
app/controllers/users/sessions_controller.rb:18:in `new_guest'
The password generation was generated by SecureRandom.urlsafe_base64
, but I had to fix this.
app/models/user.rb
def self.guest
find_or_create_by!(email: '[email protected]') do |user|
user.password = SecureRandom.urlsafe_base64
user.name = "Guest"
user.username = "guest"
user.confirmed_at = Time.now
end
end
The validation was a regular expression as follows.
app/models/user.rb
validate :password_complexity
def password_complexity
return if password.blank? || password =~ /^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{8,70}$/
errors.add :password, 'Must be at least 6 characters in length and must contain one uppercase letter, one lowercase letter, one number, and one special character.'
end
--Development environment uses Docker --Ruby: Uses 2.6.3 Docker image
The correction method was to generate a password as shown below.
An array of 0-9, a-z, A-Z, and special characters is randomly extracted by the sample
method with 4 characters each.
▼ ▼ ▼
Concatenate each array with the `` `summethod ▼ ▼ ▼
shuffleShuffle the values in the array with the method ▼ ▼ ▼
join```Concatenate array string to string with method
app/models/user.rb
def self.guest
find_or_create_by!(email: '[email protected]') do |user|
user.password = [
[*0..9].sample(4),
[*'a'..'z'].sample(4),
[*'A'..'Z'].sample(4),
['#', '?', '!', '@', '$', '%', '^', '&', '*', '-'].sample(4),
].sum([]).shuffle.join
user.name = "Guest"
user.username = "guest"
user.confirmed_at = Time.now
end
end
At first, I searched for a way to generate a password in a regular expression with the `` `SecureRandom``` method, but I couldn't find it and came up with the above method. Do you feel a little forced? It feels like this, but I'm glad that I can now generate passwords within regular expressions.
Recommended Posts