Rails 中的密码加密
Password encryption in Rails
我有 User 模型并在其上使用 Devise gem。在我的应用程序中,我有一个管理员用户可以注册其他用户(example:clients)。然后这些用户可以使用随机生成的密码自行登录。 (但是没有人可以自己注册,只有admin可以注册用户。)
当我从其他登录用户创建用户时,即管理员用户创建另一个用户,我想生成一些随机密码,加密并保存到数据库。
如何加密密码,使其与 Devise 授权一起使用。我想我必须使用与 Devise 相同的方法?
我想要这样的东西:
编辑:
def create
@user = User.new(user_params)
# set @user.password to some random encrypted password
@user.save
end
所以每个创建的用户都会得到一些随机密码。
我问这个问题的原因是,我认为如果我的 encryption/decription 与使用的设备不匹配,用户将无法使用他们的密码登录,因为当他们登录时,他们的输入是通过设计的加密加密。
您应该将 :database_authenticatable
作为 设计模块之一 在您的 User
模型中。
来自 Devise,它说
Database Authenticatable: encrypts and stores a password in the
database to validate the authenticity of a user while signing in. The
authentication can be done both through POST requests or HTTP Basic
Authentication.
如果您正在使用 Devise 并且启用了 :database_authenticable
,则您根本不需要您描述的内容。
Devise 在保存到数据库时会自动加密,并且在读回时不会解密,但是当您将其存储在密码字段中时,它可以是纯文本, Devise 只会在你写 时为你处理 (所以它会保持纯文本,直到你 save
)。
因此在您的控制器中创建新用户,您只需执行以下操作:
def create
# I assume your form will pass a `params[:password]` in plain text too
@user = User.new(user_params)
@user.password_confirmation = params[:password]
@user.save
end
这应该足以满足您的目的,不需要匹配设计加密
更新 1:
另外要生成随机密码,您可以执行以下操作:
require 'securerandom'
def create
# I assume your form will pass a `params[:password]` in plain text too
@password = SecureRandom.hex(16)
@user = User.new(user_params.to_h.merge(password: @password, password_confirmation: @password))
@user.save
# Remember to display `@password` in some way to the user
end
我有 User 模型并在其上使用 Devise gem。在我的应用程序中,我有一个管理员用户可以注册其他用户(example:clients)。然后这些用户可以使用随机生成的密码自行登录。 (但是没有人可以自己注册,只有admin可以注册用户。)
当我从其他登录用户创建用户时,即管理员用户创建另一个用户,我想生成一些随机密码,加密并保存到数据库。
如何加密密码,使其与 Devise 授权一起使用。我想我必须使用与 Devise 相同的方法?
我想要这样的东西: 编辑:
def create
@user = User.new(user_params)
# set @user.password to some random encrypted password
@user.save
end
我问这个问题的原因是,我认为如果我的 encryption/decription 与使用的设备不匹配,用户将无法使用他们的密码登录,因为当他们登录时,他们的输入是通过设计的加密加密。
您应该将 :database_authenticatable
作为 设计模块之一 在您的 User
模型中。
来自 Devise,它说
Database Authenticatable: encrypts and stores a password in the database to validate the authenticity of a user while signing in. The authentication can be done both through POST requests or HTTP Basic Authentication.
如果您正在使用 Devise 并且启用了 :database_authenticable
,则您根本不需要您描述的内容。
Devise 在保存到数据库时会自动加密,并且在读回时不会解密,但是当您将其存储在密码字段中时,它可以是纯文本, Devise 只会在你写 时为你处理 (所以它会保持纯文本,直到你 save
)。
因此在您的控制器中创建新用户,您只需执行以下操作:
def create
# I assume your form will pass a `params[:password]` in plain text too
@user = User.new(user_params)
@user.password_confirmation = params[:password]
@user.save
end
这应该足以满足您的目的,不需要匹配设计加密
更新 1:
另外要生成随机密码,您可以执行以下操作:
require 'securerandom'
def create
# I assume your form will pass a `params[:password]` in plain text too
@password = SecureRandom.hex(16)
@user = User.new(user_params.to_h.merge(password: @password, password_confirmation: @password))
@user.save
# Remember to display `@password` in some way to the user
end