[英]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.