登录后重定向用户仅当它在 root_path 上时 [英] Redirect user after log in only if it's on root_path
问题描述
我的 Rails 应用程序上有一个不受用户保护的 root_path
,即它是一个简单的门户主页,带有一个登录表单.
I have a root_path
on my Rails application that is not user-protected i.e. it's a simple portal homepage, with a login form.
用户登录后,我希望它转到dashboard_path
.
After the users log in, I'd like it to go to dashboard_path
.
我已经这样做了:
def signed_in_root_path(scope_or_resource)
dashboard_path
end
这显然应该在用户登录时使用,我不希望它转到 root_path
,同时仍然让用户在尝试点击时返回上一页一个限制区域,它要么超时,要么没有登录.
This apparently should be used when an user signs in, and I don't want it to go to the root_path
, while still keeping the user going back to a previous page if it tries to hit a restricted area and it's either timed out or not logged in.
即:
restricted_page -> 登录 ->stricted_page_but_logged_in
restricted_page -> login -> restricted_page_but_logged_in
我不想改变这种行为,这就是为什么我没有使用 after_sign_in_path
,但 想要重定向它,如果它在 root_path
,或任何不需要用户身份验证的路由.
I don't want to change this behavior, and that's why I haven't used after_sign_in_path
, but want to redirect it if it's on root_path
, or any route that doesn't require user authentication.
我的问题是这不起作用.登录后,我被重定向回 root_path
,我认为这是因为 after_sign_in_path
之前被触发.
My problem is that this is not working. After signing in, I'm getting redirected back to root_path
, which I believe is because of after_sign_in_path
getting triggered before.
有没有办法做到这一点?谢谢!
Is there any way to do this? Thanks!
这在我第二次登录时起作用,即我转到 root_path
,登录,收到提示我已登录的 flash 消息,然后再次输入用户名和密码root_path
上的表单.我成功地被重定向到 dashboard_path
.仍然不是我想要的行为.
This works the second time I log in, i.e. I go to root_path
, log in, gets the flash message stating me that I'm logged in, and enter username and password again on the form on root_path
. I successfully get redirected to dashboard_path
. Still, not quite the behavior I want.
推荐答案
只是一个想法
您可以定义两个根 url,一个用于登录 url 指向仪表板,第二个用于未登录用户指向登录页面
You can define two root url one for signed in url which will point to dashboard and second for non signed in users which will point to login page
根据一些约束定义不同的根 url在routes.rb
define different root url based on some constraints in routes.rb
constraints(AuthenticatedUser) do
root :to => "dashboard"
end
未登录用户的根网址
root :to=>"users/signin"
然后在 lib/authenticated_user.rb 中创建类 AuthenticatedUser
then create class AuthenticatedUser in lib/authenticated_user.rb
class AuthenticatedUser
def self.matches?(request)
user_signed_in?
end
end
现在,如果用户登录 root_url 将指向仪表板,否则它将指向登录页面
now if user is signed in root_url will point to dashboard else it will point to signin page
您也可以使用(尚未测试)创建两个根
Your can also create two roots using(did not tested it yet)
root :to => "dashboard", :constraints => {user_signed_in?}
root :to => "users/signin"
更多关于约束http://edgeguides.rubyonrails.org/routing.html#request-based-constraints
注意
url 的优先级是基于创建的顺序,首先创建 ->最高优先级资源
The priority of url is based upon order of creation, first created -> highest priority resources
这篇关于登录后重定向用户仅当它在 root_path 上时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!