2

我在 WordPress 站点的子目录中部署了一个 Rails 应用程序 (5.2.4.1)。我的控制器调用 before_action 方法来验证用户

class ClientsController < ApplicationController
  before_action :authenticate unless ENV["RAILS_ENV"] == "development"
  before_action :set_agent
  before_action :set_client, only: [:show, :edit, :update, :destroy]

如果用户没有来自域上另一个站点的 cookie,则调用 ApplicationController 中的方法进行重定向

class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception

  private
  def authenticate
    logger.info("Authenticate method called") # outputs on first load, not subsequent
    if request.cookies.collect{|c| c.grep(/cookiename/)}.blank?
      redirect_to 'https://example.com', status: :moved_permanently and return
    end
  end

如果我转到私人浏览器(所以没有 cookie)并尝试访问控制器,我会按预期重定向。

如果我输入相同的 URL,则不会调用 authenticate 方法。控制器呈现动作。我在该方法中放置了一条日志记录语句,authenticate并且在进一步的页面加载时不会调用它。

难道我做错了什么?我希望在每次页面加载时调用 before_action 方法。其他两个(set_agent 和 set_client)可能也没有被调用,但由于它们根据路由参数设置实例变量,因此不会引起问题。

4

2 回答 2

0

问题原来是我如何检查是否没有 cookie。

request.cookies.collect{|c| c.grep(/cookiename/)}.blank?

会在有 cookie 和 [[], [], []].blank 的页面加载时返回一个空数组数组(例如 [[], [], []] )?评估为假。

这不是我想要的。

我切换到按键检查cookie(这应该首先发生),这解决了这个问题。

知道为什么我在后续加载时没有看到记录器输出。我想我只是错过了它。

于 2021-01-14T16:54:12.557 回答
0

您应该使用 before_action 的正确语法

class ClientsController < ApplicationController
  before_action :authenticate, :unless => ENV["RAILS_ENV"] == "development"
  .
  .
  .

还有一些例子是

before_action :verify_authenticity_token_with_exception, :only => [:update_data], :unless => :ignore_csrf?
before_filter :authenticate_user!, :except => [:some_method]
于 2021-01-13T03:59:09.557 回答