Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to auto-generate passwords in Rails Devise?

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!

like image 395
ohho Avatar asked Sep 10 '10 01:09

ohho


2 Answers

Use the Devise.friendly_token method:

password_length = 6
password = Devise.friendly_token.first(password_length)
User.create!(:email => '[email protected]', :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.

like image 72
jeanmartin Avatar answered Sep 20 '22 23:09

jeanmartin


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

password = User.generate_token('password')
User.create!(:email => '[email protected]', :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).

like image 20
Dave Rapin Avatar answered Sep 23 '22 23:09

Dave Rapin