用户身份验证:为无效的电子邮件/密码输入提供单独的错误
在我的 Rails 应用程序中,我尝试分别为无效的 :email
和 :password
生成单独的 flash.now[:alert]
。因此,如果用户输入了正确的电子邮件地址但密码错误,:alert
会警告用户密码无效,反之亦然。这是我的 SessionsController 中的内容:
def create
if user = User.authenticate(params[:email], params[:password])
session[:user_id] = user.id
redirect_to user.profile, :notice => "Logged in successfully"
elsif user.email != params[:email]
session[:email] = @user.email
flash.now[:alert] = "Invalid email. Try again!"
render :action => 'new'
else
session[:password] = @user.password
flash.now[:alert] = "Invalid password. Try again!"
render :action => 'new'
end
end
渲染它为我提供了一个未定义的电子邮件方法。谁能帮我弄清楚我做错了什么?
In my Rails app I'm trying to produce a separate flash.now[:alert]
for invalid :email
and :password
, respectively. So if a user enters the correct email but wrong password, the :alert
warns the user of an invalid password and vice versa. Here's what I have in my SessionsController:
def create
if user = User.authenticate(params[:email], params[:password])
session[:user_id] = user.id
redirect_to user.profile, :notice => "Logged in successfully"
elsif user.email != params[:email]
session[:email] = @user.email
flash.now[:alert] = "Invalid email. Try again!"
render :action => 'new'
else
session[:password] = @user.password
flash.now[:alert] = "Invalid password. Try again!"
render :action => 'new'
end
end
Rendering this gives me an undefined method for email. Can anyone help me figure out what I'm doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
免责声明:显然这是一个非常糟糕的主意,因为攻击者可以继续尝试电子邮件,直到找到匹配的电子邮件,然后他可以开始尝试他知道存在于您的数据库中的这封电子邮件的密码,但是您正在问,所以这取决于你决定是否这样做。
显然,您的身份验证方法仅在电子邮件和密码匹配时才返回用户,更改您的身份验证方法以返回布尔值和用户(如果有可用)。它看起来有点像这样:
然后,在你的控制器上:
这应该可以工作。
DISCLAIMER: Obviously this is a really bad idea as an attacker could keep on trying emails until he found one that did match and then he could start trying passwords for this email he knows exists at your database, but you're asking, so it's up to you deciding to do this or not.
Your authenticate method obviously only returns the user if the email and password did match, change your authenticate method to return a boolean and a user if there is any available. It would look somewhat like this:
Then, at your controller:
And this should work.