登录后狂欢重定向

时间:2014-08-06 17:51:06

标签: ruby-on-rails ruby-on-rails-4 spree

Spree 2.3 with spree_auth_devise,Rails 4.0

我尝试根据用户的角色登录后重定向用户。最好的解决方案是在初始化程序中修改一个路径,一个la Devise,但这些似乎不适用于Spree。下一个最好的解决方案是在会话控制器上创建一个装饰器,但我找不到这个控制器,当我尝试跟踪rake routes

中的信息时,我也无法访问它

如何在Spree应用程序中根据用户的角色将用户重定向到新位置?

更新 覆盖after_sign_in_path_for(resource)方法会导致方法被触发,但仍会重新路由到admin_path

# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
  def after_sign_in_path_for(resource)
    byebug # this is triggered
    root_path
  end
end

### OR ####

class ApplicationController < ActionController::Base
  def after_sign_in_path_for(resource)
    byebug # this is triggered
    if spree_current_user.has_spree_role?("admin")
      admin_path
    elsif spree_current_user.has_spree_role?("designer")
      new_designers_spree_variant_path
    else
      root_path
    end
  end
end

我的尝试记录在这里: https://gist.github.com/asteel1981/0f258260974f4d748fb5

提前致谢。

3 个答案:

答案 0 :(得分:5)

感谢@mvidaurre花了一些时间跟我钻研。

问题是spree_auth_devise有第二种尝试重新路由到最后一页尝试的方法,这意味着我不仅需要修改after_sign_in_path_for方法,还需要修改Spree方法redirect_back_or_default(默认)。

此外,由于我的用户通过admin / sign_in路由登录,我需要访问Spree :: Admin :: UserSessionsController,而不仅仅是Spree :: UserSessionsController。

我早期的解决方案如下:

# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
  def after_sign_in_path_for(resource)
    if spree_current_user.has_spree_role?("admin")
      admin_path
    elsif spree_current_user.has_spree_role?("designer")
      '/designers/spree_variants/new' #rails helper gives the wrong path, not sure why
    else
      root_path
    end
  end
end

# app/controllers/spree/admin/user_sessions_controller.rb
Spree::Admin::UserSessionsController.class_eval do
  def redirect_back_or_default(default)
    if spree_current_user && spree_current_user.has_spree_role?("admin")
      redirect_to(session["spree_user_return_to"] || default)
      session["spree_user_return_to"] = nil
    else
      redirect_to(default)
    end
  end
end

相关的狂欢源代码在这里: https://github.com/spree/spree_auth_devise/blob/8cb2d325b2c1da02cbe137404d8dda89cc1613a2/lib/controllers/backend/spree/admin/user_sessions_controller.rb

答案 1 :(得分:1)

感谢您在评论中的回答。 spree_auth_devise定义了Spree::UserSessionsController您可以装饰控制器并使用以下所述的方法:How To: redirect to a specific page on successful sign in

您可以为以下方式实施自定义方法:

def after_sign_in_path_for(resource)
  current_user_path
end

也许是这样的:

def after_sign_in_path_for(resource)
  if spree_current_user.has_spree_role?("designer")
    root_path
  elsif spree_current_user.has_spree_role?("admin")
    admin_path
  else
    root_path
  end
end

答案 2 :(得分:0)

Spree文档似乎涵盖了这一点,请查看:

http://guides.spreecommerce.com/developer/authentication.html

这似乎是你想要实现目标的良好起点。