随机生成的密码Rails 3.1

bob*_*nte 16 random passwords ruby-on-rails

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

问题是我在轨道上是全新的,所以即使是基本的东西对我来说也很难......

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

Users_Controller:

class UsersController < ApplicationController
  skip_before_filter :is_connected?, :only => [: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
Run Code Online (Sandbox Code Playgroud)

User_model:

class User < ActiveRecord::Base
  attr_accessible :email
  has_secure_password
  validates_presence_of :password, :email, :on => :create
end
Run Code Online (Sandbox Code Playgroud)

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

Fre*_*ung 45

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

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

require 'securerandom'
SecureRandom.hex(8)
Run Code Online (Sandbox Code Playgroud)

应该做得很好(你可能想考虑SecureRandom.urlsafe_base64一个更紧凑的表示相同数量的实际随机性)


Tha*_* kp 5

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

rand_password=('0'..'z').to_a.shuffle.first(8).join
Run Code Online (Sandbox Code Playgroud)

希望它会有所帮助.

  • 您不应该使用安全随机数生成密码吗? (3认同)
  • 我使用`rand_password =(('0'..'9').to_a +('a'..'z').to_a +('A'..'Z').to_a).shuffle.first( 8).join`只获得没有特殊字符的字母数字符号 (2认同)