简体   繁体   中英

How to create subdomain automatically when customer is registering in Rails Application?

假设当客户在示例Rails应用程序中注册时,我们有一个用于subdomain的文本字段。如何自动创建该子域并允许我们客户的用户仅从该子域登录?

Since you're using a simple text field for the subdomain , you only need to change Devise :

#config/routes.rb
scope constraints: SubDomain do
   devise_for :users
end

#lib/sub_domain.rb
module SubDomain

    def initializer(router)
        @router = router
    end

    def self.matches?(request)
        User.exists? subdomain: request.subdomain
    end

end

#app/models/user.rb
class User < ActiveRecord::Base
   devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, request_keys: [:subdomain]

   def self.find_for_authentication(warden_conditions)
      where(:email => warden_conditions[:email], :subdomain => warden_conditions[:subdomain]).first
   end
end

Because the session_store will be scoped to a single tld (top level domain), you'll only have to change the above.


Bonus

A better way to do it would be to automatically set the subdomain, from their username or something.

You'll be best using friendly_id to create a "slug" (which you can alias as subdomain ):

#Gemfile
gem 'friendly_id', '~> 5.1'

# You'll have to follow friendly_id's install instructions

#app/models/user.rb
class User < ActiveRecord::Base
   extend FriendlyID
   friendly_id :username, use: [:slugged, :finders]
   alias_attribute :subdomain, :slug
end

This will automatically set the user's subdomain, which you'll be able to use with the code in the top part of the answer to direct them to the appropriate actions etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM