Ruby-on-rails 如何在设计中验证用户的密码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4320921/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to verify a user's password in Devise
提问by poporul
I'm having a problem matching user password using devise gem in rails. User password stored on my db which is encrypted_password and i am trying to find user by password, but I don't understand how to match password from form and encrypted_password in my db.
我在使用 rails 中的 devise gem 匹配用户密码时遇到问题。用户密码存储在我的数据库中,它是 encrypted_password,我试图通过密码查找用户,但我不明白如何在我的数据库中匹配表单中的密码和 encrypted_password。
User.find_by_email_and_password(params[:user][:email], params[:user][:password])
回答by joshaidan
I think this is a better, and more elegant way of doing it:
我认为这是一种更好、更优雅的方式:
user = User.find_by_email(params[:user][:email])
user.valid_password?(params[:user][:password])
The other method where you generate the digest from the user instance was giving me protected method errors.
从用户实例生成摘要的另一种方法是给我受保护的方法错误。
回答by Sheharyar
Use Devise Methods
使用设计方法
Devise provides you with built-in methods to verify a user's password:
Devise 为您提供了验证用户密码的内置方法:
user = User.find_for_authentication(email: params[:user][:email])
user.valid_password?(params[:user][:password])
For Rails 4+ with Strong Params, you can do something like this:
对于带有 Strong Params 的 Rails 4+,您可以执行以下操作:
def login
user = User.find_for_authentication(email: login_params[:email])
if user.valid_password?(login_params[:password])
user.remember_me = login_params[:remember_me]
sign_in_and_redirect(user, event: :authentication)
end
end
private
def login_params
params.require(:user).permit(:email, :password, :remember_me)
end
回答by Amrit Dhungana
I think the better one will be this
我认为更好的是这个
valid_password = User.find_by_email(params[:user][:email]).valid_password?(params[:user][:password])
回答by Roshan
I would suggest this.
我会建议这个。
user = User.where("email=? OR username=?", email_or_username, email_or_username).first.valid_password?(user_password)

