随机生成的密码Rails 3.1

出于新的Web应用程序的目的,我需要在我的注册页面(仅限管理员)上只有一个电子邮件字段。

问题是我对rails非常陌生,所以即使是基本的东西对我来说也很难……

我使用Railscast#270创建了我的身份validation,它使用has_secure_password方法。 现在,一切都很好,除了我不需要所有这些公牛…我还想使用Action Mailer将生成的密码发送到他的电子邮件地址。 hex(8)密码是完美的(我已经看过SecureRandom,但似乎已经折旧了)

Users_Controller:

class UsersController  [:new, :create] def new @user = User.new end def create @user = User.new(params[:user]) if @user.save # Tell the Mailer to send a welcome Email after save Mailer.confirm_email(@user).deliver redirect_to root_url, :notice => "Signed up!" else render "new" end end end 

User_model:

 class User  :create end 

现在,在我看来,我有2个字段。 但正如我先前所说,我只想要一个。 我想继续使用has_secure_password,这似乎提供了关于hash / salt的相当好的安全性。

Rails提供ActiveSupport::SecureRandom ,它们(取决于Ruby版本)只是Ruby的SecureRandom的桥梁,或者在旧版本的Ruby上重新实现它(如果我的内存是正确的,则在1.8.7中添加了SecureRandom

现在,Rails支持的所有Ruby版本都不再需要SecureRandom内置的ActiveSupport::SecureRandom ,并且已被弃用。 SecureRandom本身无处可去 –

 require 'securerandom' SecureRandom.hex(8) 

应该没问题(您可能需要考虑SecureRandom.urlsafe_base64以获得相同数量的实际随机性的更紧凑的表示)

这是一个简单的随机密码代码,带有lenth 8

 rand_password=('0'..'z').to_a.shuffle.first(8).join 

希望它会有所帮助。

有时来自Rails的东西被弃用,因为它们复制了已添加到Ruby核心的function,而SecureRandom似乎就是其中之一。

您可以使用任何这些随机生成器方法来生成一次性密码。

 class User < ActiveRecord::Base def self.encrypt(pass, salt) return Digest::MD5.hexdigest(pass.to_s+salt.to_s) end def self.random_string(len) chars = ("a".."z").to_a + ("A".."Z").to_a + ("0".."9").to_a newpass = "" 1.upto(len) { |i| newpass << chars[rand(chars.size-1)] } return newpass end def new_password=(pass) return if pass.blank? self.salt = User.random_string(10) if self.salt.nil? self.password_hash = User.encrypt(pass, self.salt) end end 

创建Randomunique令牌/密码

 class User < ActiveRecord::Base before_create :generate_password def generate_password self.password = loop do random_token = SecureRandom.urlsafe_base64 # If you are using FFaker gem then you can use it otherwise # SecureRandom is great choice # random_token = FFaker::Internet.password break random_token unless User.exists?(password: random_token) end end end 

这里的主要对象是生成随机令牌,不要在数据库中重复该令牌。 对于某些情况,如生成unique tokenunique invoice number等,它可能非常有用