2016-05-31 58 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。 –