gpt4 book ai didi

ruby-on-rails - spree Action require_login 在分配给 before_action 过滤器时创建重定向循环

转载 作者:数据小太阳 更新时间:2023-10-29 08:03:46 33 4
gpt4 key购买 nike

我试图限制整个 Spree (Rails) 应用程序,以便只有登录的用户才能访问该站点。我在 Rails 文档中读到

If a "before" filter renders or redirects, the action will not run

这是导致此循环的 app/controllers/application_controller.rb 中的代码

class ApplicationController < ActionController::Base

before_action :require_login

private

def logged_in?
spree_current_user != nil
end

def require_login
unless logged_in?
flash[:error] = spree_current_user
# supposed to halt request cycle -
# http://guides.rubyonrails.org/action_controller_overview.html#filters
redirect_to spree_login_path
end
end

end

最佳答案

通过更改 skip_before_action 的位置,我能够在不呈现自定义页面的情况下让它工作。根据您链接到的 Rails 文档:

In this example the filter is added to ApplicationController and thus all controllers in the application inherit it. This will make everything in the application require the user to be logged in in order to use it. For obvious reasons (the user wouldn't be able to log in in the first place!), not all controllers or actions should require this. You can prevent this filter from running before particular actions with skip_before_action:

class LoginsController < ApplicationController   
skip_before_action :require_login, only: [:new, :create]
end

这意味着 skip_before_action 应该进入您的 LoginsController 而不是您的 ApplicationsController。我能够通过拆分来让它工作:

class ApplicationController < ActionController::Base
before_action :require_login

private

def logged_in?
spree_current_user != nil
end

def require_login
unless logged_in?
flash[:error] = "Please Login or Sign Up"
redirect_to spree_login_path
end
end
end

然后我用了一个controller decoratorskip_before_action 添加到 sessions_controller:

Spree::UserSessionsController.class_eval do
skip_before_action :require_login

end

您可能需要将装饰器和 skip_before_action 添加到影响登录的其他 Controller ,并且您希望用户可以访问(如密码重置和注册)

关于ruby-on-rails - spree Action require_login 在分配给 before_action 过滤器时创建重定向循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29264430/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com