更新时间:2023-12-06 09:01:16
这是对上一个 SO 问题的回答 - 设计:注册登录尝试有答案.
设计控制器中的创建操作调用warden.authenticate!,它尝试使用提供的参数对用户进行身份验证.如果身份验证失败,则进行身份验证!将调用设计失败应用程序,然后运行 SessionsController#new 操作.请注意,如果身份验证失败,您为创建操作设置的任何过滤器都不会运行.
The create action in the devise controller calls warden.authenticate!, which attempts to authenticate the user with the supplied params. If authentication fails then authenticate! will call the devise failure app, which then runs the SessionsController#new action. Note, any filters you have for the create action will not run if authentication fails.
因此,解决方案是在新操作之后添加一个过滤器,该过滤器检查 env[warden.options"] 的内容并采取适当的操作.
So the solution is to add a filter after the new action which checks the contents of env["warden.options"] and takes the appropriate action.
我尝试了这个建议,并且能够记录成功的 &登录尝试失败.这是相关的控制器代码:
I tried out the suggestion, and was able to log both the successful & failed login attempts. Here is the relevant controller code:
class SessionsController < Devise::SessionsController
after_filter :log_failed_login, :only => :new
def create
super
::Rails.logger.info "
***
Successful login with email_id : #{request.filtered_parameters["user"]}
***
"
end
private
def log_failed_login
::Rails.logger.info "
***
Failed login with email_id : #{request.filtered_parameters["user"]}
***
" if failed_login?
end
def failed_login?
(options = env["warden.options"]) && options[:action] == "unauthenticated"
end
end
日志中有以下条目:
Started POST "/users/sign_in"
...
...
***
Successful login with email_id : {"email"=>...
***
...
...
Completed 302 Found
Started POST "/users/sign_in"
...
...
Completed 401 Unauthorized
Processing by SessionsController#new as HTML
...
...
***
Failed login with email_id : {"email"=>...
***
...
...
Completed 302 Found