ohh*_*hho 31 ruby-on-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!
小智 77
password_length = 6
password = Devise.friendly_token.first(password_length)
User.create!(:email => 'someone@something.com', :password => password, :password_confirmation => password)
Run Code Online (Sandbox Code Playgroud)
仅供参考:Devise.friendly_token返回20个字符的令牌.在上面的例子中,我们password_length使用String#firstRails提供的方法切断生成的令牌的第一个字符.
一种选择是使用Devise.generate_token.即
password = User.generate_token('password')
User.create!(:email => 'someone@something.com', :password => password, :password_confirmation => password)
Run Code Online (Sandbox Code Playgroud)
这个选项在Devise中已经有很长一段时间了.请参考其他答案(friendly_token).
我正在使用devise-securitygem 并且有password_complexity如下特定要求:
config.password_complexity = { digit: 1, lower: 1, upper: 1 }
如果您使用此代码:Devise.friendly_token.first(password_length)来生成密码,您并不总能保证获得与您的复杂性相匹配的密码。
所以我写了一个密码生成器,它会尊重你的password_complexity并且会生成一个随机的投诉密码:
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
Run Code Online (Sandbox Code Playgroud)
您可以按如下方式使用它:
PasswordGenerator.new.password # "qHc165ku"