-
Notifications
You must be signed in to change notification settings - Fork 322
/
client.py
43 lines (32 loc) · 1.35 KB
/
client.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
from django.test import RequestFactory, Client
from django_tenants.middleware.main import TenantMainMiddleware
from django.http import HttpRequest
from django.contrib.auth import authenticate
class BaseTenantRequestFactory:
tm = TenantMainMiddleware(lambda r: r)
def __init__(self, tenant, **defaults):
super().__init__(**defaults)
self.tenant = tenant
def generic(self, *args, **kwargs):
if "HTTP_HOST" not in kwargs:
kwargs["HTTP_HOST"] = self.tenant.get_primary_domain().domain
request = super().generic(*args, **kwargs)
# Assign the tenant to the request object
request.tenant = self.tenant
return request
class TenantRequestFactory(BaseTenantRequestFactory, RequestFactory):
pass
class TenantClient(BaseTenantRequestFactory, Client):
def login(self, **credentials):
# Create a dummy HttpRequest object and add HTTP_HOST
request = HttpRequest()
request.META['HTTP_HOST'] = self.tenant.get_primary_domain().domain
request.tenant = self.tenant
# Authenticate using django contrib's authenticate which passes the request on
# to custom backends
user = authenticate(request, **credentials)
if user:
super(TenantClient, self)._login(user)
return True
else:
return False