首页 > 解决方案 > Rails 6 mysubdomain.lvh.me 重定向你太多次

问题描述

我正在构建一个带有子域的 rails 6 应用程序(一种多租户方法,但不使用单独的模式)。

我正在尝试构建一个 before_action,我可以在我的应用程序控制器上设置它来评估当用户登陆网站时是否有一个与 request.subdomain 调用匹配的帐户。

例如,

Hammer corp 的一个成员想要登录,当该请求发出时,他们将继续到hammer.lvh.me 我希望我的前过滤器看到该请求与现有帐户匹配,并说coolio并将它们重定向到他们各自的登录页面。如果没有帐户与子域匹配(即错字),我希望将它们重定向到我的 root_url 或注册页面。

我目前有这个

def verify_account!
  if @account = Account.find_by(subdomain: request.subdomain).present?
    redirect_to login_url(subdomain: @account.subdomain)
  else
    redirect_to root_url(subdomain: nil)
  end
end

当我尝试使用有效的子域访问该站点时,我确实可以看到它想将我重定向到 url 中的登录页面,但是我redirected you too many times在浏览器中得到了。

不太确定如何着手解决这个问题?任何帮助都会很棒!

编辑#1 - 完整的application_controller.rb

class ApplicationController < ActionController::Base
  before_action :configure_permitted_parameters, if: :devise_controller?
  before_action :verify_account!
  # before_action :set_account

  def after_sign_in_path_for(resource)
    stored_location_for(resource) || dashboard_path
  end

  def after_sign_out_path_for(resource)
    root_path
  end

  private

    def verify_account!
      if @account = Account.find_by(subdomain: request.subdomain).present?
        redirect_to login_url(subdomain: @account.subdomain)
      else
        redirect_to root_url(subdomain: nil)
      end
    end

    # def require_account!
      # redirect_to root_url(subdomain: nil) if !@account.present?
      # flash[:error] = "An account is required to access this page. Please sign up or proceed to your_company.loadze.co to login"
    # end

    def set_account
      @account = Account.find_by(subdomain: request.subdomain)
      # byebug
    end

    def configure_permitted_parameters
      devise_parameter_sanitizer.permit(:sign_up, keys: [:f_name, :l_name, account_attributes: [:company_name]])
    end

end

编辑#2:添加服务器输出

Started GET "/login" for 127.0.0.1 at 2019-09-30 04:29:16 -0600
Processing by Devise::SessionsController#new as HTML
  Account Load (0.2ms)  SELECT "accounts".* FROM "accounts" WHERE "accounts"."subdomain" = $1 LIMIT $2  [["subdomain", "tauren_group"], ["LIMIT", 1]]
  ↳ app/controllers/application_controller.rb:17:in `verify_account!'
Redirected to http://tauren_group.lvh.me:3000/login
Filter chain halted as :verify_account! rendered or redirected
Completed 302 Found in 2ms (ActiveRecord: 0.2ms | Allocations: 865)

标签: ruby-on-rails

解决方案


当应用程序被重定向到登录屏幕时,它会再次被重定向,因为它再次进入 if 块。尝试这个:

def verify_account!
  if @account = Account.find_by(subdomain: request.subdomain).present?
    return if request.url == login_url(subdomain: @account.subdomain)

    redirect_to login_url(subdomain: @account.subdomain)
  else
    redirect_to root_url(subdomain: nil)
  end
end

推荐阅读