[英]Rails, devise, SPA, redirect to custom url (with param in query string) after logout and login (sign_out, sign_in)
我有一个带有devise
gem的默认Rails应用,有些路线完全是SPA(单页应用)。
如果我进入该SPA页面(假设为“ /home
”)并且未通过身份验证(或会话结束),则会将我重定向至:
localhost:3000/users/sign_out
” localhost:3000/users/sign_in
” 一切都很好,但是。
现在我需要的是,如果我说“ /home/jobs
”,就像在未通过身份验证或会话结束之前那样,它将重定向到:
localhost:3000/users/sign_out?continue=localhost:3000/home/jobs
”(我使用javascript“ window.location.replace”做到这一点) localhost:3000/users/sign_in
” continue
”参数,并且登录后无法继续“ Continue” URL。 我知道after_sign_in_path_for
和after_sign_out_path_for
但是我认为这不适用于查询字符串中的参数,对吗?
这是一个疯狂的场景吗?
这是混合SPA路由和非SPA路由的问题之一。 我认为最好放弃一些前期时间,将设计转换为仅api响应,然后将用户会话路由也设置为SPA。
我不确定是否无法在devise控制器中访问请求参数,应该检查一下,也许可以,但是如果没有,至少可以通过其他方法解决此问题,那就是需要一个before_action
在您的application_controller.rb
上application_controller.rb
任何设计逻辑之前,只需根据参数分配一个会话密钥,然后在after_action
删除,例如(仅作说明):
#application_controller.rb
before_action :set_continue
#...
def set_continue
if params[:continue]
session[:continue] = params[:continue]
end
end
然后,这将允许您在after_sign_in_path
上使用它:
def after_sign_in_path_for(resource)
if session[:continue]
navigation = session[:continue]
session[:continue] = nil
navigation
else
your_regular_path_helper #or super I guess
end
end
您可以使用stored_location_for
和store_location_for
。 此示例摘自Devise Wiki的“ 如何:成功登录后重定向到特定页面” 。
# some_controller.rb (or even the application_controller)
if params[:redirect_to].present?
store_location_for(resource, params[:redirect_to])
end
# application_controller.rb
class ApplicationController < ActionController::Base
protect_from_forgery
protected
def after_sign_in_path_for(resource)
sign_in_url = new_user_session_url
if request.referer == sign_in_url
super
else
stored_location_for(resource) || request.referer || root_path
end
end
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.