我的数据库中有一个用户表,我想做的是有一个 在创建时为每个用户生成随机密码,然后发送给该用户 他们的邮件地址。我想知道如何分配随机 密码。
我认为我有以下内容:
<p>
<div id="p1"><%= t('.username')%></div>
<%= f.text_field :username %>
</p>
<p>
<div id="p1"><%= t('.email')%></div>
<%= f.text_field :email %>
</p>
<p class="button"><%= f.submit 'Create Account' %></p>
我的控制器中有以下内容:
def create
@user = User.new(params[:user])
respond_to do |format|
if @user.save
Notifier.user_created(@user).deliver
format.html { redirect_to @user, notice: 'User was successfully created.' }
format.json { render json: @user, status: :created, location: @user }
else
format.html { render action: "new" }
format.json { render json: @user.errors, status::unprocessable_entity }
end
end
end
我的用户模型中有以下内容:
attr_accessor :password
before_save :encrypt_password
def encrypt_password
if password.present?
self.password_salt = BCrypt::Engine.generate_salt
self.password_hash = BCrypt::Engine.hash_secret(password, password_salt)
end
end
def self.random_string(len)
#generate a random password consisting of strings and digits
chars = ("a".."z").to_a + ("A".."Z").to_a + ("0".."9").to_a password = ""
1.upto(len) { |i| password << chars[rand(chars.size-1)]}
return password
end
def self.authenticate(email, password)
user = find_by_email(email)
if user && user.password_hash == BCrypt::Engine.hash_secret(password, user.password_salt)
user
else
nil
end
end
我必须删除我的密码。存在吗? line因为它不存在但是我有随机字符串代码,我只需要将它分配给hash / salt。
答案 0 :(得分:2)
def create
@user = User.new(params[:user])
@user.password = User.random_string(10) #set it with the size of the password you want
respond_to do |format|
if @user.save
Notifier.user_created(@user).deliver
format.html { redirect_to @user, notice: 'User was successfully created.' }
format.json { render json: @user, status: :created, location: @user }
else
format.html { render action: "new" }
format.json { render json: @user.errors, status::unprocessable_entity }
end
end
end
玩得开心!
答案 1 :(得分:1)
我想,你可以修改你的encrypt_password;)
before_save :encrypt_password
def encrypt_password
self.password = User.random_string(X) unless password.present?
self.password_salt = BCrypt::Engine.generate_salt
self.password_hash = BCrypt::Engine.hash_secret(password, password_salt)
end
编辑:如果您只想在创建时加密密码,可以使用'before_create'而不是'before_save'