Devise Ajax登录:“ sessions#create”仅在成功时才呈现“ create.js.erb” [英] Devise Ajax login: 'sessions#create' only render 'create.js.erb' when it succeed
问题描述
我的目标是用Devise实现Ajax登录解决方案,并且模式变化最少。我已经部分达到了它,但是失败回调有一个问题。让我解释一下这种情况:
My goal is to implement an Ajax login solution with Devise with the minimal change of patterns. I already reached it partially, but there is one problem with the failure callback. Let me explain the scenario:
- 以模态显示登录表单,并带有
remote:true
Rails / UJS约定(确定); - 创建自定义的
会话
控制器,然后将Devise指向它(确定); - 创建一个JS视图文件
create.js.erb
来响应sessions#create
操作(问题);
- Display login form in a modal with
remote: true
Rails/UJS convention (OK); - Create a custom
sessions
controller and point Devise to it (OK); - Create a JS view file
create.js.erb
to respond forsessions#create
action (PROBLEM);
问题:我的 create.js.erb
仅包含 alert( Test ok)
。当我使用正确的凭据提交 sessions#new
表单时,将执行文件 create.js.erb
,<显示code>警报。但是如果使用了错误的凭据,则不会这样,返回 401未经授权状态和
create.js.erb
会被忽略。
The problem: My create.js.erb
only contains an alert("Test ok")
. When I submit the sessions#new
form with the correct credentials the file create.js.erb
is executed, the alert
is shown. But with wrong credentials it doesn't, returning 401 Unauthorized
status and create.js.erb
is ignored.
也许有人知道在登录失败时使 create.js.erb
运行的快捷技巧。这样,我无需创建独立的Ajax脚本或更改整个会话
控制器。
Maybe someone know a quick trick to make create.js.erb
run when login fail. This way I don't need to create a standalone Ajax script or change entire sessions
controller.
谢谢,
VERSIONS:
Rails 4.0.2
Devise 3.2.2
自定义会话控制器:
class Website::SessionsController < ::Devise::SessionsController
respond_to :js # without it neither on success create.js.erb runs
layout false # action `new` pure html which is rendered in a modal box
end
sessions / create.js.erb
sessions/create.js.erb
alert("Test ok");
登录失败时的服务器日志:
Server log when login fails:
Started POST "/users/sign_in" for 127.0.0.1 at 2014-03-27 09:59:47 -0300
Processing by Website::SessionsController#create as JS
Parameters: {"utf8"=>"✓", "user"=>{"email"=>"", "password"=>"[FILTERED]"}, "commit"=>"Fazer login"}
Completed 401 Unauthorized in 1ms
推荐答案
出现问题的原因是:
warden.authenticate!(...)
warden.authenticate!(...)
它会引发异常,并且之后不渲染视图。
It raise the exception and don't render your view after.
您应该为您的SessionsController#create操作覆盖自己的行为。例如这样的
You should to override SessionsController#create action for your own behavior. For example like this:
def create
self.resource = warden.authenticate(auth_options)
if resource && resource.active_for_authentication?
...
sign_in(resource_name, resource)
...
else
...
end
end
这篇关于Devise Ajax登录:“ sessions#create”仅在成功时才呈现“ create.js.erb”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!