[Ruby/Rails] How to generate a password in a regular expression

at first

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.

error contents

スクリーンショット 2020-12-30 11.15.57.png

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

Prerequisite/implementation environment

--Development environment uses Docker --Ruby: Uses 2.6.3 Docker image

Fixes

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 the 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

[Ruby/Rails] How to generate a password in a regular expression
How to automatically generate a constructor in Eclipse
How to insert a video in Rails
How to publish a library in jCenter
How to update user edits in Rails Devise without entering a password
How to run a djUnit task in Ant
How to add a classpath in Spring Boot
How to create a theme in Liferay 7 / DXP
How to implement a like feature in Rails
How to easily create a pull-down in Rails
How to generate a primary key using @GeneratedValue
[Ruby] How to generate a random alphabet string
How to solve an Expression Problem in Java
How to make a follow function in Rails
Regular expression for password
How to clear all data in a particular table
How to create a Java environment in just 3 seconds
How to implement a like feature in Ajax in Rails
How to update devise user information without a password
How to create a Spring Boot project in IntelliJ
How to manually generate a JWT with Rails Knock
How to create a data URI (base64) in Java
How to launch another command in a Ruby program
How to display a browser preview in VS Code
How to write a date comparison search in Rails
[Java] How to execute tasks on a regular basis
How to store Rakuten API data in a table
How to mock a super method call in PowerMock
How to generate / verify ID token in Java Memo
How to convert A to a and a to A using AND and OR in Java
Ruby Regular Expression Extracts from a specific string to a string
How to convert a file to a byte array in Java
[Rails] How to load JavaScript in a specific view
How to write a core mod in Minecraft Forge 1.15.2
Notes on how to use regular expressions in Java
How to leave a comment
How to insert a video
How to create a method
How to change a string in an array to a number in Ruby
How to create a placeholder part to use in the IN clause
How to store a string from ArrayList to String in Java (Personal)
How to display a graph in Ruby on Rails (LazyHighChart)
How to add the same Indexes in a nested array
Mapping to a class with a value object in How to MyBatis
How to develop and register a Sota app in Java
How to simulate uploading a post-object form to OSS in Java
How to set up a proxy with authentication in Feign
How to use Lombok in Spring
How to add columns to a table
How to run JUnit in Eclipse
How to iterate infinitely in Ruby
[Rails] How to write in Japanese
How to run Ant in Gradle
How to make a jar file with no dependencies in Maven
How to make a Java container
How to master programming in 3 months
A little regular expression story Part 1
How to sign a Minecraft MOD
How to make a JDBC driver
How to implement a job that uses Java API in JobScheduler
How to create a new Gradle + Java + Jar project in Intellij 2016.03