I'm writing an application with rails. I got an error when I implemented the login function with a test account, so keep a record of the solution I took.
Ruby 2.6.5 Rails 6.0.3.3
I implemented the test login function with the following code.
Controller
class Users::SessionsController < Devise::SessionsController
#Log in as a guest user
def new_guest
user = User.find_or_create_by!(nickname: 'Guest user', email: '[email protected]') do |user|
user.password = SecureRandom.alphanumeric
end
sign_in user
redirect_to root_path, notice: 'You have logged in as a guest user.'
end
end
Model
#Set validation to allow only half-width alphanumeric characters
PASSWORD_REGEX = /\A(?=.*?[a-z])(?=.*?[\d])[a-z\d]+\z/i.freeze
validates_format_of :password, with: PASSWORD_REGEX, on: :create, message: 'Please set including both half-width alphabetic characters and half-width numbers.'
Even in the development environment, no error occurred and the test passed, so when I deployed to the production environment, "Sorry, something went wrong." Was displayed.
Because SecureRandom.alphanumeric
issued a password with only letters.
In the first place, SecureRandom is explained as follows in Reference.
A module that provides an interface for a secure random number generator. Suitable for HTTP session keys, etc.
And alphanumeric
is a kind of method of SecureRandom module, which generates random alphanumeric characters. However, it is not always generated by mixing alphanumeric characters.
console
pry(main)> SecureRandom.alphanumeric
=> "NNCMHbfUbHRQmbwW"
The probability is not high, but as mentioned above, a password with only letters may be generated.
class Users::SessionsController < Devise::SessionsController
#Log in as a guest user
def new_guest
user = User.find_or_create_by!(nickname: 'Guest user', email: '[email protected]') do |user|
user.password = SecureRandom.alphanumeric(10) + [*'a'..'z'].sample(1).join + [*'0'..'9'].sample(1).join
end
sign_in user
redirect_to root_path, notice: 'You have logged in as a guest user.'
end
end
It has become a brute force, but `` ['a'..'z'] .sample (1) .join + [ '0' .. '9'] .sample (1) .joinBy setting
to make sure that two characters of letters + numbers are entered at the end of the password, passwords with only letters or numbers are not generated.
Recommended Posts