How to auto-generate passwords in Rails Devise?

Viewed 20175

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 user's password from time to time, and then the admin will email the new username and password to his users.

Assume the admin has the knowledge of direct SQL on the MySQL database, how can the generated usernames/passwords recognized by Devise? Thanks!

4 Answers

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).

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"

Related