如何将设计 parent_controller 用于设计继承控制器,但跳过 ActiveAdmin 设计控制器?

How to use devise parent_controller for devise inherited controller but skip for ActiveAdmin devise controller?

我正在开发基于 Api 的应用程序,site.com(客户端应用程序),api。site.com(服务器应用程序)

在我的api.site.com中,有密码、确认控制器,都是从Devise控制器继承而来的。 Devise父控制器默认是Application控制器,但是Devise继承的控制器需要通过ApiBaseControllerapi_authentication动作。因此,Devise.rb 具有以下配置:

config.parent_controller = 'ApiBaseController'

Api 身份验证现在工作正常。

ApiBaseController示例代码:

class ApiBaseController < ApplicationController
  before_action :api_authentication

  def api_authentication
    api_key = request.headers['Api-Key']
    @app = Application.find_by_api_key(api_key) if api_key
    unless @app
     return render json: { errors: { message: 'Something went wrong, contact admin', code: '1000' } }
    end
  end
end

现在我正在使用 ActiveAdmin,安装 ActiveAdmin 后我尝试在浏览器上打开 http://localhost:3000/admin/login,我在浏览器上看到以下错误响应而不是活动管理员登录页面:

{"errors":{"message":"Something went wrong, contact admin","code":1000}}

我检查了这个问题,我意识到 active_admin/devise/sessions 控制器也通过了 ApiBaseController。这是因为我们将父控制器设置为 ApiBaseController (config.parent_controller = 'ApiBaseController')。我删除了代码,ActiveAdmin 工作正常。

但是密码、确认控制器没有通过 ApiBaseController api_authentication() 因为我删除了 Devise 配置 (config.parent_controller = 'ApiBaseController')。

所以如果你们明白了问题,请告诉我解决方案。

综上所述,我需要所有 api Devise 继承控制器需要通过 ApiBaseController 进行 api_authentication() 检查,而 ActiveAdmin Devise 控制器不需要通过 ApiBaseController.

提前致谢。

您只需在 application_controller.rb 中编写 api 身份验证逻辑,然后在您的密码控制器或任何您想要的地方使用 before_filter

class ApplicationController < ActionController::Base

 private

 def api_authentication
    api_key = request.headers['Api-Key']
    @app = Application.find_by_api_key(api_key) if api_key
    unless @app
      return render json: { errors: { message: 'Something went wrong, contact admin', code: '1000' } }
    end
  end
 end

并在您的控制器中使用 before_filter :api_authentication

class PasswordsController < Devise::PasswordsController
  before_filter :api_authentication

  .......
end

我正在寻找在 Devise parent_controller 中添加条件的方法,但我没有找到 Devise 的任何解决方案。但是,我通过添加一些代码解决了它。

class ApiBaseController < ApplicationController
  before_action :api_authentication

  def api_authentication
   return true if params[:controller].include?("active_admin/devise/")
    api_key = request.headers['Api-Key']
    @app = Application.find_by_api_key(api_key) if api_key
    unless @app
     return render json: { errors: { message: 'Something went wrong, contact admin', code: '1000' } }
    end
  end
end