Develop: how to quickly reset all user passwords

I have a rake task that (among other things) clones my production database to my local machine and resets all user passwords to password (or something else).

My current implementation looks something like this:

 User.find_each do |user| user.password = 'password' user.save end 

And it works great. But now that we have more than 1000 users, it is becoming rather slow, and it is sure that it will be worse.

EDIT

Good. Here is a partial answer:

 Devise.stretches = 1 User.find_each do |user| user.password = 'password' user.save end Devise.stretches = 10 

This led me to increase speed by 5-10 times. Although it is still probably slow compared to the SQL-based solution, it is still a very good improvement. This should scale to at least 10,000 users.

I can still chat with the SQL solution if I have the time.

I will leave this question open. If anyone has a better solution, send a message.

Final Answer / Best Solution

As a few comments were suggested, the fastest solution is to perform a bulk update through SQL. Now Devise allows you to directly set encrypted_password :

 sample_user = User.last sample_user.password = "password" encrypted_password = sample_user.encrypted_password User.update_all(encrypted_password: encrypted_password) 

Basically, we set a password for one user, then we can use their encrypted_password to perform a bulk update. This solution should scale for almost any number of users.

Credit @vladCovaliov for offering this solution in the comment below.

+4
source share
1 answer

Usually I would say write the sql you want, for example.

 ActiveRecord::Base.connection.execute(' update users set encrypted_password = 'password') 

However, usually the password is encrypted and you directly encrypt it using MD5 or an authorization / authentication mechanism such as Devise or Authlogic. In this case, you actually create or change the password by passing the password and password confirmation values ​​(when creating the entry in Rails) that must match. If they match, the password is encrypted and actually stored in the database. For this reason, you need to do this one by one if you are not using the hash algorithm in your direct sql.

It can be as simple as

 ActiveRecord::Base.connection.execute(' update users set password = md5('password')) 
+2
source

Source: https://habr.com/ru/post/1433490/


All Articles