[英]Devise: How to redirect to the previous page after login, but only if previous page requires authentication?
使用Devise gem,我如何在登錄后重定向到上一頁,但前提是前一頁需要身份驗證(否則重定向到我定義的特定頁面)?
所需場景:
/my-private-account
> Devise 檢測到需要身份驗證並重定向到登錄 > 成功登錄 > 重定向到/my-private-account
/
(不需要身份驗證)> 訪問/login
> 成功登錄 > 重定向到特定頁面,例如。 /dashboard
/about
(不需要認證)>訪問/login
>成功登錄>重定向到/dashboard
Devise Wiki幾乎涵蓋了這一點,但他們的答案重定向回所有頁面。 例如。 從/
(不需要認證)>訪問/login
>成功登錄>重定向回/
我的身份驗證在路由中定義:
# routes.rb
authenticate :user do
resources :events
end
# application_controller.rb
class ApplicationController < ActionController::Base
before_action :store_user_location!, if: :storable_location?
private
# Redirect back to current page after sign in
# ref: https://github.com/heartcombo/devise/wiki/How-To:-Redirect-back-to-current-page-after-sign-in,-sign-out,-sign-up,-update
def storable_location?
request.get? && is_navigational_format? && !devise_controller? && !request.xhr?
end
def store_user_location!
# :user is the scope we are authenticating
store_location_for(:user, request.fullpath)
end
def after_sign_in_path_for(resource)
stored_location_for(resource) || dashboard_path
end
end
有沒有辦法檢查路由是否需要身份驗證? 然后我可以覆蓋after_sign_in_path_for
例如。
def after_sign_in_path_for(resource)
if stored_location_for(resource).requires_authentication? # something like this...?
stored_location_for(resource)
else
events_path
end
end
還是我在錯誤的方向上解決這個問題,有沒有更好的方法?
最后,我還需要注意什么才能使這項工作也適用於omniauth?
我認為您實際需要覆蓋的是storable_location?
方法,這樣你就不會存儲你不想 go 回來的位置。
例如,在處理/
或/about
路由的 controller 中,您可以覆蓋該storable_location?
方法總是返回 false 以便不存儲這些位置,然后不會設置stored_location_for
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.