2

这是我的会话控制器:

class SessionsController < Devise::SessionsController
  respond_to :json

  def create
    resource = warden.authenticate!(scope: resource_name, recall: "#{controller_path}#failure")
    sign_in(resource_name, resource)
    return render json: { success: true, path: root_path }
  end

  def failure
    return render json: { success: false, errors: ['Login information is incorrect, please try again'] }
  end
end

用户#active_for_authentication

  def active_for_authentication?
    super && active_flag == 1 && has_active_subscription?
  end

服务器响应:

Started POST "/users/sign_in" for 127.0.0.1 at 2013-07-29 15:11:39 -0500
Processing by SessionsController#create as JSON
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"ozQ00tw9rRWExCmlIyIZR07ovnTLab5w0W44cLAKwA4=", "user"=>{"email"=>"dennis+dlksjfdkfjsd@recruittalk.com", "password"=>"[FILTERED]"}, "commit"=>"Sign In"}
  User Load (1.0ms)  SELECT "users".* FROM "users" WHERE "users"."type" IN ('User', 'Athlete', 'Coach') AND "users"."email" = 'dennis+dlksjfdkfjsd@recruittalk.com' LIMIT 1
   (0.6ms)  BEGIN
  AccountType Load (0.5ms)  SELECT "account_types".* FROM "account_types" WHERE "account_types"."id" = $1 LIMIT 1  [["id", 3]]
  AccountType Load (0.7ms)  SELECT "account_types".* FROM "account_types" WHERE "account_types"."id" = 3 LIMIT 1
   (0.5ms)  COMMIT
Completed 401 Unauthorized in 338ms


Started GET "/users/sign_in.json" for 127.0.0.1 at 2013-07-29 15:11:40 -0500
Processing by SessionsController#new as JSON
Completed 200 OK in 13ms (Views: 1.6ms | ActiveRecord: 0.0ms)

由于某种原因,浏览器中的请求包含一个带有电子邮件和密码作为属性的用户对象。无论出于何种原因,失败的 json 都不会呈现。不知道我做错了什么

编辑

#Devise    
config.http_authenticatable_on_xhr = false

咖啡脚本:

  $(document).on 'ajax:success', '.user_modal_form', (e, data) ->
      context = $(this)
      if data.success
        $('input[type="submit"]', context).hide()
        $('.spinner', context).show()

        if data.path?
          window.location.href = data.path
        else
          location.reload()
      else
        e.preventDefault()
        if data.errors?
          $('.error-messages', context).html(data.errors).parent().show()
        else
          $('button', context).show()
          $('.spinner', context).hide()
          $('.alert', context).show()

      false
4

3 回答 3

4

这就是我为那些以后可能会偶然发现的人准备的东西......

#config/initializers/devise.rb:
config.http_authenticatable_on_xhr = true
config.navigational_formats = [:"*/*", "*/*", :html, :json]

会话控制器

class SessionsController < Devise::SessionsController
  respond_to :json

  def create
    resource = warden.authenticate!(scope: resource_name, recall: "#{controller_path}#failure")
    sign_in(resource_name, resource)
    return render json: { success: true, path: root_path }
  end

  def failure
    return render json: { success: false, errors: ['Login information is incorrect, please try again'] }
  end
end

路线

# I have implemented STI (Single Table Inheritance) into my app, therefore I skip sessions and passwords for the :user scope    
devise_for :users, skip: :registrations, controllers: { sessions: "sessions", passwords: "passwords" }

用户模型

  def active_for_authentication?
    super && active_flag == 1 && has_active_subscription?
  end

  def inactive_message
    "Your subscription has been canceled or has expired."
  end

咖啡脚本:

  $(document).on 'ajax:success', '.user_modal_form', (e, data) ->
      context = $(this)
      log data
      if data.success
        $('input[type="submit"]', context).hide()
        $('.spinner', context).show()

        if data.path?
          window.location.href = data.path
        else
          location.reload()
      else
        e.preventDefault()
        if data.errors?
          $('.error-messages', context).html(data.errors).parent().show()
        else
          $('button', context).show()
          $('.spinner', context).hide()
          $('.alert', context).show()

      false
    .on 'ajax:error', '.user_modal_form', (event, xhr, ajaxOptions, thrownError) ->
      json = $.parseJSON(xhr.responseText)
      $('.error-messages', $(this)).html(json.error).parent().show()
于 2013-07-30T13:27:28.593 回答
1

将以下代码添加到会话控制器,以在控制器上创建failure自定义 json 响应的方法:

def auth_options
  super.merge(recall: "#{controller_path}#failure")
end

def failure
  render json: {error: "Login failed"}, status: :unauthorized
end

recall显然is的默认选项#{controller_path}#new,我认为这可能对 html 有意义。如果要将其限制为仅 json 请求,则可以在 auth_options 中使用 respond_to。

于 2014-05-29T01:20:42.747 回答
0

我不确定您为什么要获取带有登录凭据的对象,但 Devise 通过它的 FailureApp 处理错误 - 确保您覆盖它,以便在触发 401 时,守望者会调用自定义操作。

这是在您的设计初始化程序中完成的,config/initializers/devise.rb

将此添加到初始化程序并重新启动服务器:

config.http_authenticatable_on_xhr = false
config.navigational_formats = [:html, :json]
于 2013-07-29T21:24:15.830 回答