Skip to content

Commit

Permalink
Merge pull request #4 from py-package/hotfix/connection
Browse files Browse the repository at this point in the history
Hotfix/connection
  • Loading branch information
yubarajshrestha committed Jul 10, 2022
2 parents 3ed5215 + 8035aba commit 68287e2
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 16 deletions.
2 changes: 1 addition & 1 deletion setup.py
Expand Up @@ -8,7 +8,7 @@
# Versions should comply with PEP440. For a discussion on single-sourcing
# the version across setup.py and the project code, see
# https://packaging.python.org/en/latest/single_source_version.html
version="0.0.3",
version="0.0.4",
packages=[
"multitenancy",
"multitenancy.commands",
Expand Down
16 changes: 1 addition & 15 deletions src/multitenancy/middlewares/tenant_finder_middleware.py
@@ -1,25 +1,11 @@
from masonite.middleware import Middleware
from ..models.Tenant import Tenant


class TenantFinderMiddleware(Middleware):
"""Middleware to find the tenant for the current request."""

def before(self, request, response):
from wsgi import application

"""Find the tenant for the current request."""
tenant = (
Tenant.where("domain", request.get_host())
.or_where("database", request.get_subdomain())
.first()
)
if tenant:
request.tenant = tenant
tenancy = application.make("multitenancy")
tenancy.setup_connection(tenant)

return request
return request.app.make("multitenancy").find_tenant(request)

def after(self, request, response):
"""Return the response."""
Expand Down
31 changes: 31 additions & 0 deletions src/multitenancy/multitenancy.py
@@ -1,3 +1,4 @@
from masonite.request.request import Request
from .models.Tenant import Tenant
from masonite.configuration import config
from masoniteorm.connections import ConnectionResolver
Expand Down Expand Up @@ -39,3 +40,33 @@ def setup_connection(self, tenant):
def delete(self, tenant):
"""Deletes a tenant."""
tenant.delete()

def get_subdomain(self, request: Request):
"""Returns the subdomain for the current request."""
hosts = [request.environ.get("HTTP_HOST"), request.environ.get("HTTP_X_FORWARDED_HOST")]
subdomains = []
for host in hosts:
if host:
items = host.split(".")
if len(items) > 2:
subdomains.append(items[0])
return subdomains, hosts

def __reset_connection(self):
ConnectionResolver().set_connection_details(config("database.databases"))

def find_tenant(self, request: Request):
"""Finds the tenant for the current request."""
subdomains, hosts = self.get_subdomain(request)
subdomains = tuple(subdomains)
hosts = tuple(hosts)
print(hosts, subdomains)
try:
self.__reset_connection()
tenant = Tenant.where_raw("database in {database}".format(database=subdomains)).first()
if tenant:
self.setup_connection(tenant)
request.tenant = tenant
except Exception as e:
print(e)
return request

0 comments on commit 68287e2

Please sign in to comment.