Rails 4 + Devise + AJAX:已完成401未经授权

时间:2014-07-01 18:45:15

标签: ruby-on-rails

我有一个设计会话控制器的子类:

class SessionsController < Devise::SessionsController
  respond_to :html, :js

  def create
    login_process do
      super
    end
  end

  private

    def login_process
      if !anonymous_user?
        old_user = guest_user
      end
      yield
      if user_signed_in?
        current_user.cart.replace_cart_items!(old_user.cart.cart_items) unless old_user.cart.cart_items.empty?
      end
    end

end 

我从其网站粘贴的表单,用于在其他网页上自定义登录表单:https://github.com/plataformatec/devise/wiki/How-To:-Display-a-custom-sign_in-form-anywhere-in-your-app

    <div class="log_in_div">
        <h3>Log in</h3>
        <%= form_tag session_path(:user), remote: true do %>
            <div>
                <%= label_tag 'user[email]', 'Email' %>
              <%= text_field_tag 'user[email]' %>
            </div>
            <div>
                <%= label_tag "user[password]", "Password" %>
              <%= password_field_tag 'user[password]' %>
            </div>

          <%= check_box_tag 'user[remember_me]' %>
          <%= label_tag 'user[remember_me]', 'Remember me' %><br>
          <%= submit_tag "Log in" %>
          <%= link_to "Forgot your password?", new_password_path(:user) %>
        <% end %>
    </div>

但是,当我通过浏览器提交表单时,我得到了这个:

    Processing by SessionsController#create as JS
      Parameters: {"utf8"=>"✓", "user"=>{"email"=>"gfdgdgd", "password"=>"[FILTERED]"}, "commit"=>"Log in"}
    Completed 401 Unauthorized in 3ms

有谁知道发生了什么事?

2 个答案:

答案 0 :(得分:0)

如果你使用ajax调用设计登录 -

设置&lt; config.http_authenticatable_on_xhr = false&gt;在设计初始化程序

并设置&lt;%= csrf_meta_tags%&gt;在应用程序布局中

答案 1 :(得分:0)

skip_before_filter :authenticate_user!添加到SessionsController。