2016-05-31 54 views
2

我正在开发基于API的应用程序,site.com(客户端应用),api.site.com(服务器应用程序)如何使用devise parent_controller设计继承控制器,但跳过ActiveAdmin设计控制器?

在我api.site.com,有密码,确认控制器,它是从继承设计控制器。默认情况下Devise父控制器是Application控制器,但Devise继承控制器需要通过ApiBaseController api_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,我看到了下面的浏览器,而不是主动管理登录页面错误响应:

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

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

所以,如果你们已经理解了这个问题,请让我知道解决方案。总之,我需要所有的api Devise继承控制器需要通过ApiBaseController进行api_authentication()检查,并且ActiveAdmin Devise控制器不需要通过ApiBaseController传递。

在此先感谢。

回答

2

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

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 
3

你只需在你的密码控制器或任何你想要的地方写你的API验证逻辑application_controller.rb并使用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 
+0

是的,但是我不希望里面ApplicationController中的任何代码,我们已经有ApiBaseController –

+1

那么你可以使用'before_action:api_authentication,如果:?json_request'在您的API基地控制器 –

+0

感谢您的建议,我会尝试这个。顺便说一句,我解决了它,我期待Devise的解决方案,因为我将来可能会有许多父母喜欢ApiBaseController。 –