ruby-on-rails - 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)
解决方案
当应用程序被重定向到登录屏幕时,它会再次被重定向,因为它再次进入 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
推荐阅读
- symfony - 如果在树枝中为空,则设置默认值
- python - 在 django rest 框架中的嵌套序列化程序中上传图像
- mybatis - 添加@Transactional函数解决游标继续打开后卡在批量插入
- pre-commit - 为我的存储库设置 Talisman 时提交更改时出现意外错误
- php - 如何按降序动态排序年份范围数组
- android-studio - 更新到新的 android studio artic fox (2020.3.1) 后出现主题问题
- symfony - 使用 botman 发送电子邮件
- javascript - 将大型 XML 文件读入 Javascript 的问题
- java - 如何从 CSV 等数据集中“垂直”读取
- jquery - 如何仅在短时间内更改按钮的值