![](/img/trans.png)
[英]Rerouting custom routes when user is not authenticated (Devise, rails gem)
[英]Rails4+Devise: “hide” routes when user is not authenticated
我試圖使未經身份驗證的用戶的管理后台頁面“不可見”。 這意味着當用戶轉到/admin/my_controller
我想顯示404自定義頁面,使他相信這只是常規的404。當然,當用戶通過身份驗證后,他將正確訪問控制器。
所以我幾乎所有工作都在進行,我只是缺少設計/維護部分。 我在我的Rails應用程序中正確配置了404錯誤救援(在我名為ErrorsController
的控制器中實現),因此當有人進入不存在的uri如/nothing_here
,我的自定義404頁面會正確顯示。
我正在嘗試使用ErrorsController
作為failure_app
,它幾乎可以正常工作,除了如果我使用不正確的憑據登錄會收到異常。 我當然只是錯過了最后一個細節。 例外是
AbstractController::ActionNotFound at /unauthenticated
The action 'create' could not be found for ErrorsController
顯然,應該從SessionController
而不是ErrorsController
調用create
動作。 這是最后遺漏的一點。 如何實現呢?
在config / application.rb中
config.exceptions_app = self.routes
在config / routes.rb中
get '*dummy', to: 'errors#index'
應用程序/控制器/ errors_controller.rb
class ErrorsController < ApplicationController
def index
display_404
end
end
在config / initializers / devise.rb中
config.warden do |manager|
manager.failure_app = ErrorsController
end
AbstractController::ActionNotFound at /unauthenticated The action 'create' could not be found for ErrorsController
引發AbstractController::ActionNotFound at /unauthenticated The action 'create' could not be found for ErrorsController
當用戶未登錄時,處理錯誤的更合適的方法是將方法添加到應用程序控制器中。 例如display_404
在display_404
方法中添加
raise ActionController::RoutingError.new('Not Found')
調用此方法時,它將引發Rails的錯誤頁面,並在日志文件中記錄“未找到”。 在開發過程中,它將顯示在屏幕上,但在生產過程中將僅在日志文件中找到,因此有可能添加'User was not signed in'
內容。
然后使用
before_action do
unless admin_signed_in?
display_404
end
end
如果訪客未登錄,將顯示錯誤頁面。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.