我已经使用Apartment (1.2.0) 和Devise (4.2.0) 设置了 Rails 5 应用程序。由于某些 DDNS 问题,存在应用程序只能在以下条件下访问的限制app.myapp.com(注意 subdomain app)。myapp.com重定向到app.myapp.com.
我的用例是每个注册应用程序的用户(租户)都应该通过他们的子域(例如tenant.myapp.com)访问他们的特定数据。用户不应局限于其子域。基本上应该可以从任何子域登录。重定向到租户的正确子域由ApplicationController. 根据设计标准,登录页面位于app.myapp.com/users/sign_in. 这就是问题开始的地方:
由于“电子邮件或密码不正确”错误,用户无法登录。
在开发中,我玩了一点。从 登录lvh.me效果很好。用户已登录并被重定向到他们的子域。尝试相同app.lvh.me会导致上述问题。
我已将会话存储设置为:
# /config/initializers/session_store.rb
Rails.application.config.session_store :cookie_store, key: '_myapp_session', domain: {
production: '.app.myapp.com',
staging: '.app.myapp.com',
development: '.app.lvh.me'
}.fetch(Rails.env.to_sym, :all)
我也尝试过以下也不起作用:
Rails.application.config.session_store :cookie_store, key: '_myapp_session', domain: :all
我需要做什么才能从任何子域登录?
一个测试用例是:
用户user1访问 urlapp.myapp.com/users/sign_in会提供他们的凭据,因此会登录并重定向到user1.myapp.com.
奖励:user1访问 urlanother_user.myapp.com/users/sign_in提供他们的凭据,因此登录并重定向到user1.myapp.com.
编辑
其他相关配置:
# /config/initializers/apartment.rb
config.excluded_models = %w{ User }
config.tenant_names = lambda { User.pluck :subdomain }
config.tld_length = 2
Rails.application.config.middleware.insert_before Warden::Manager, Apartment::Elevators::FirstSubdomain
Apartment::Elevators::FirstSubdomain.excluded_subdomains = ExcludedSubdomains.subdomains
和
# /app/classes/excluded_subdomains.rb
class ExcludedSubdomains
def self.subdomains
%w( www admin test public private staging app web net )
end # subdomains
end # class
和
# /app/models/user.rb
class User < ApplicationRecord
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable,
:confirmable, :lockable
after_create :create_tenant
after_destroy :delete_tenant
# other stuff
def create_tenant
Apartment::Tenant.create(subdomain)
end # create_tenant
def delete_tenant
Apartment::Tenant.drop(subdomain)
end # delete_tenant
end # class
和
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
before_action :authenticate_user!
before_action :redirect_to_subdomain
private
def redirect_to_subdomain
return if self.is_a?(DeviseController) || self.is_a?(Users::OnboardingController)
if current_user.present? && request.subdomain != current_user.subdomain
redirect_to main_index_url(subdomain: current_user.subdomain)
end # if
end # redirect_to_subdomain
def after_sign_in_path_for(resource_or_scope)
users_onboarding_start_url(subdomain: resource_or_scope.subdomain)
end # after_sign_in_path_for
def after_sign_out_path_for(resource_or_scope)
successful_logout_url(subdomain: '')
end # after_sign_out_path_for
end # class