如何随机生成密码Rails 4?

时间:2016-02-01 05:31:32

标签: ruby-on-rails-4 web random web-applications passwords

我已经完成了Railstutorial.org的书。现在我想改变一下,只有管理员可以注册一个名字和电子邮件的新用户。密码自动生成并发送给用户电子邮件。我坚持如何为用户随机生成密码。 有人能帮我吗 ?非常感谢。

model/user.fb
class User < ActiveRecord::Base
  attr_accessor :remember_token
  before_save { self.email = email.downcase }
  validates :name,  presence: true, length: { maximum: 50 }
  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
  validates :email, presence: true, length: { maximum: 255 },
                    format: { with: VALID_EMAIL_REGEX },
                    uniqueness: { case_sensitive: false }
  has_secure_password
  validates :password, presence: true, length: { minimum: 6 }, on: :create // this line will be removed

  # Returns the hash digest of the given string.
  def User.digest(string)
    cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST :
                                                  BCrypt::Engine.cost
    BCrypt::Password.create(string, cost: cost)
  end

  # Returns a random token.
  def User.new_token
    SecureRandom.urlsafe_base64
  end

  # Remembers a user in the database for use in persistent sessions.
  def remember
    self.remember_token = User.new_token
    update_attribute(:remember_digest, User.digest(remember_token))
  end

  # Returns true if the given token matches the digest.
  def authenticated?(remember_token)
    BCrypt::Password.new(remember_digest).is_password?(remember_token)
  end

   # Forgets a user.
  def forget
    update_attribute(:remember_digest, nil)
  end

  # Returns true if the given token matches the digest.
  def authenticated?(remember_token)
    return false if remember_digest.nil?
    BCrypt::Password.new(remember_digest).is_password?(remember_token)
  end
end

controller/admin/user_controller.rb
class Admin::UsersController < ApplicationController
  before_action :admin_user 
  before_action :logged_in_user 
  def new
    @user = User.new
  end

  def index
    @users = User.where(admin: false)
  end

  def show
    @user = User.find(params[:id])
    @subjects = @user.subjects
  end

  def create
    @user = User.new(user_params)
    if @user.save
      flash[:success] = "create new user successfully"
      redirect_to admin_users_url
    else
      render 'new'
    end  
  end

  def edit
    @user = User.find(params[:id])
  end

  def update
    @user = User.find(params[:id])
    if @user.update_attributes(user_params)
      flash[:success] = "Profile updated!"
      redirect_to admin_users_url
    else
      render 'edit'
    end
  end

  def destroy
    User.find(params[:id]).destroy
    flash[:success] = "User deleted!"
    redirect_to admin_users_url
  end

  private

    def user_params
      params.require(:user).permit(:name, :email, :password, :password_confirmation, :address, :phone, :admin)
    end
end

views/admin/new.html
<% provide(:title, 'Sign up') %>
<h1>add user</h1>

<div class="row">
  <div class="col-md-6 col-md-offset-3">
    <%= form_for [:admin, @user] do |f| %>
      <%= render 'shared/error_messages', object: @user %>

      <%= f.label :name %>
      <%= f.text_field :name, class: 'form-control' %>

      <%= f.label :email %>
      <%= f.email_field :email, class: 'form-control' %>

      <%= f.label :address %>
      <%= f.text_field :address, class: 'form-control' %>

      <%= f.label :phone %>
      <%= f.text_field :phone, class: 'form-control' %>

      <%= f.label :password %> // this line will be removed
      <%= f.password_field :password, class: 'form-control' %>// this line will be removed

      <%= f.label :password_confirmation, "Confirmation" %>// this line will be removed
      <%= f.password_field :password_confirmation, class: 'form-control' %>// this line will be removed

      <%= f.label :admin, 'Is this admin?' %>
      <%= f.select :admin, options_for_select(['false', 'true']) %><br>

      <%= f.submit "Save", class: "btn btn-primary" %>
    <% end %>
  </div>
</div>

1 个答案:

答案 0 :(得分:1)

在下面的代码中,用户就是模型。

在这里,您将检查使用其他所有用户密码生成的安全密码,如果新生成的密码与任何密码不匹配,则可以将其用于新用户。

def generate_password
 loop do
    seed = "--#{rand(10000000)}--#{Time.now}--#{rand(10000000)}"
    secure_password = Digest::SHA1.hexdigest(seed)[0,8]
    break secure_password unless User.exists?(password: secure_password)
  end
end