2018-07-12 16:00:35 +00:00
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
#
|
|
|
|
|
2018-07-13 07:05:46 +00:00
|
|
|
from .utils import get_org_from_request, set_current_org
|
2022-02-17 12:13:31 +00:00
|
|
|
from rbac.models import RoleBinding
|
2018-07-12 16:00:35 +00:00
|
|
|
|
|
|
|
|
|
|
|
class OrgMiddleware:
|
|
|
|
def __init__(self, get_response):
|
|
|
|
self.get_response = get_response
|
|
|
|
|
2019-06-19 08:45:14 +00:00
|
|
|
@staticmethod
|
|
|
|
def set_permed_org_if_need(request):
|
2019-06-21 09:09:18 +00:00
|
|
|
if request.path.startswith('/api'):
|
2019-06-19 08:45:14 +00:00
|
|
|
return
|
2019-09-12 10:56:26 +00:00
|
|
|
if not request.user.is_authenticated:
|
|
|
|
return
|
2022-02-17 12:13:31 +00:00
|
|
|
|
2019-06-19 08:45:14 +00:00
|
|
|
org = get_org_from_request(request)
|
2022-02-17 12:13:31 +00:00
|
|
|
|
|
|
|
search_org = None if org.is_root() else org
|
|
|
|
has_roles = RoleBinding.objects.filter(user=request.user, org=search_org).exists()
|
|
|
|
if has_roles:
|
2019-09-12 10:56:26 +00:00
|
|
|
return
|
2019-06-19 08:45:14 +00:00
|
|
|
|
2022-02-17 12:13:31 +00:00
|
|
|
roles_bindings = RoleBinding.objects.filter(user=request.user).exclude(org=None)
|
|
|
|
if roles_bindings:
|
|
|
|
org_id = str(list(roles_bindings.values_list('org_id', flat=True))[0])
|
|
|
|
request.session['oid'] = org_id
|
|
|
|
|
2018-07-12 16:00:35 +00:00
|
|
|
def __call__(self, request):
|
2019-06-19 08:45:14 +00:00
|
|
|
self.set_permed_org_if_need(request)
|
2018-07-12 16:00:35 +00:00
|
|
|
org = get_org_from_request(request)
|
2020-04-13 02:40:13 +00:00
|
|
|
request.current_org = org
|
|
|
|
set_current_org(org)
|
2018-07-12 16:00:35 +00:00
|
|
|
response = self.get_response(request)
|
|
|
|
return response
|