How to auto-generate passwords in Rails Devise?

后端 未结 4 1179
北海茫月
北海茫月 2021-02-03 20:26

I am trying out how Devise works with one of my projects for user authentication. There is a user requirement that their admin should be able to generate a batch of username and

相关标签:
4条回答
  • 2021-02-03 20:52

    I'm using devise-security gem and have specefic password_complexity requirements as follows:

    config.password_complexity = { digit: 1, lower: 1, upper: 1 }

    If you use this code: Devise.friendly_token.first(password_length) to generate the password, you are not always guaranteed to get a password that matches your complexity.

    So I wrote a password generator that will respect your password_complexity and will generate a random complaint password:

    class PasswordGenerator
      include ActiveModel::Validations
      validates :password, 'devise_security/password_complexity': Devise.password_complexity
      attr_reader :password
    
      def initialize
        @password = Devise.friendly_token.first(Devise.password_length.first) until valid?
      end
    end
    

    You can use it as follows:

    PasswordGenerator.new.password # "qHc165ku"

    0 讨论(0)
  • 2021-02-03 21:06

    (quick caveat: I'm a rails newb)

    I tried the generate_token but it doesn't do what you think (look at the docs)

    (I'm using rails 3.0.5, and devise 1.1.7)

    What I found is that Devise will generate all that stuff for you in the background when you do:

    User.create!(:email => "me@example.com", :password => "password")
    

    Devise should create the encrypted_password, and salt for you. (pop open a console and try it out there)

    0 讨论(0)
  • 2021-02-03 21:09

    One option would be to use the Devise.generate_token. I.e.

    password = User.generate_token('password')
    User.create!(:email => 'someone@something.com', :password => password, :password_confirmation => password)
    

    This option has not been available in Devise for quite a while. Please refer to the other answer (friendly_token).

    0 讨论(0)
  • 2021-02-03 21:15

    Use the Devise.friendly_token method:

    password_length = 6
    password = Devise.friendly_token.first(password_length)
    User.create!(:email => 'someone@something.com', :password => password, :password_confirmation => password)
    

    FYI: Devise.friendly_token returns a 20 character token. In the example above, we're chopping off the first password_length characters of the generated token by using the String#first method that Rails provides.

    0 讨论(0)
提交回复
热议问题