I'm creating a multi-tenant app using devise
and apartment
gems. I'm using postgresql database. I've created a few models. 'User' model is in global namespace and it is used for authentication by devise gem. There are some other models (e.g. Project, Setting etc) which are in tenant namespace.
I've followed this tutorial for creating this multi-tenance app: https://gorails.com/episodes/multitenancy-with-apartment?autoplay=1
The multi-tenancy feature is working fine in a sense that if I login to two separate subdomains (e.g. user1.example.com and user2.example.com) from their relevant accounts (e.g. user1@gmail.com and user2@gmail.com) it works fine and I can create unique records for each tenant.
Now, the issue is, I can login to any subdomain using any email and the tenant records would be shown based on the subdomain present in address bar. e.g. I can login with user1@gmail.com
at user2.example.com
and it will succesfully autheticate and will display records of user2
tenant.
My question is, while logging in how can I check if current user's subdomain matches with the requested subdomain (on address bar), if it matches proceed with authentication and display admin dashboard and if not (logging in from wrong subdomain or from TLD) authenticate the user but redirect him to his relevant subdomain's dashboard. How can I do that?
UPDATE # 1:
I was able to restrict the user login to their specific sub-domain by using minor devise configuration. In devise.rb
file I've added :subdomain
attribute in the list of authentication keys, so it will also check for correct subdomain value together with email, however I'm not sure how to provide the subdomain value to the login form correctly. I can use a hidden field like this in login form <%= f.hidden_field :subdomain, value: request.subdomain %>
but it is hackable as user can change it's value from browser inspector.
UPDATE # 2:
I was able apply a fool proof method to restrict user login to their specific sub-domain. I've followed this method: https://github.com/plataformatec/devise/wiki/How-to:-Scope-login-to-subdomain
Now, my only issue is that user is unable to login from TLD (e.g. example.com), I want it to be possible but after login user must be redirected to their relevant sub-domain with alive session.