jumpserver/apps/orgs/mixins.py

182 lines
5.5 KiB
Python
Raw Normal View History

2018-07-12 16:00:35 +00:00
# -*- coding: utf-8 -*-
#
from werkzeug.local import Local
2018-07-12 16:00:35 +00:00
from django.db import models
2018-08-16 08:32:49 +00:00
from django.utils.translation import ugettext_lazy as _
2018-07-25 09:21:13 +00:00
from django.db.models import Q
2018-07-13 07:05:46 +00:00
from django.shortcuts import redirect
2018-07-14 16:55:05 +00:00
from django.forms import ModelForm
from django.http.response import HttpResponseForbidden
2018-08-16 08:32:49 +00:00
from django.core.exceptions import ValidationError
2018-07-12 16:00:35 +00:00
2018-08-16 08:32:49 +00:00
from common.utils import get_logger
2018-07-27 08:21:55 +00:00
from .utils import current_org, set_current_org, set_to_root_org
2018-07-19 11:24:29 +00:00
from .models import Organization
2018-07-12 16:00:35 +00:00
logger = get_logger(__file__)
tl = Local()
2018-07-12 16:00:35 +00:00
2018-07-14 16:55:05 +00:00
__all__ = [
2018-07-27 08:21:55 +00:00
'OrgManager', 'OrgViewGenericMixin', 'OrgModelMixin', 'OrgModelForm',
'RootOrgViewMixin',
2018-07-14 16:55:05 +00:00
]
2018-07-12 16:00:35 +00:00
2018-07-13 07:05:46 +00:00
class OrgManager(models.Manager):
2018-07-20 05:25:50 +00:00
2018-07-12 16:00:35 +00:00
def get_queryset(self):
queryset = super(OrgManager, self).get_queryset()
2018-07-12 16:00:35 +00:00
kwargs = {}
2018-08-16 08:32:49 +00:00
# if not hasattr(tl, 'times'):
# tl.times = 0
2018-08-06 09:16:52 +00:00
# logger.debug("[{}]>>>>>>>>>> Get query set".format(tl.times))
2018-07-12 16:00:35 +00:00
if not current_org:
2018-07-15 10:39:11 +00:00
kwargs['id'] = None
2018-07-13 07:05:46 +00:00
elif current_org.is_real():
2018-07-20 02:54:16 +00:00
kwargs['org_id'] = current_org.id
2018-07-12 16:00:35 +00:00
elif current_org.is_default():
2018-08-16 08:32:49 +00:00
queryset = queryset.filter(org_id="")
2018-07-16 06:47:06 +00:00
queryset = queryset.filter(**kwargs)
2018-07-20 05:25:50 +00:00
tl.times += 1
2018-07-13 16:47:21 +00:00
return queryset
2018-07-12 16:00:35 +00:00
def filter_by_fullname(self, fullname, field=None):
ori_org = current_org
value, org = self.model.split_fullname(fullname)
set_current_org(org)
if not field:
if hasattr(self.model, 'name'):
field = 'name'
elif hasattr(self.model, 'hostname'):
field = 'hostname'
queryset = self.get_queryset().filter(**{field: value})
set_current_org(ori_org)
return queryset
def get_object_by_fullname(self, fullname, field=None):
queryset = self.filter_by_fullname(fullname, field=field)
if len(queryset) == 1:
return queryset[0]
return None
2018-07-20 04:15:45 +00:00
def all(self):
if not current_org:
msg = 'You can `objects.set_current_org(org).all()` then run it'
return self
else:
return super(OrgManager, self).all()
2018-07-14 16:55:05 +00:00
def set_current_org(self, org):
2018-07-19 11:24:29 +00:00
if isinstance(org, str):
org = Organization.objects.get(name=org)
2018-07-14 16:55:05 +00:00
set_current_org(org)
return self
2018-07-12 16:00:35 +00:00
class OrgModelMixin(models.Model):
2018-08-16 08:32:49 +00:00
org_id = models.CharField(max_length=36, blank=True, default='', verbose_name=_("Organization"))
2018-07-12 16:00:35 +00:00
objects = OrgManager()
sep = '@'
2018-07-13 16:47:21 +00:00
def save(self, *args, **kwargs):
2018-07-12 16:00:35 +00:00
if current_org and current_org.is_real():
2018-07-20 02:54:16 +00:00
self.org_id = current_org.id
2018-07-25 09:21:13 +00:00
return super().save(*args, **kwargs)
2018-07-12 16:00:35 +00:00
@classmethod
def split_fullname(cls, fullname, sep=None):
if not sep:
sep = cls.sep
index = fullname.rfind(sep)
if index == -1:
value = fullname
org = Organization.default()
else:
value = fullname[:index]
org = Organization.get_instance(fullname[index + 1:])
return value, org
@property
def org(self):
from orgs.models import Organization
org = Organization.get_instance(self.org_id)
return org
@property
def org_name(self):
return self.org.name
@property
def fullname(self, attr=None):
name = ''
if attr and hasattr(self, attr):
name = getattr(self, attr)
elif hasattr(self, 'name'):
name = self.name
elif hasattr(self, 'hostname'):
name = self.hostname
if self.org.is_real():
return name + self.sep + self.org_name
else:
return name
2018-08-16 08:32:49 +00:00
def validate_unique(self, exclude=None):
"""
Check unique constraints on the model and raise ValidationError if any
failed.
"""
self.org_id = current_org.id if current_org.is_real() else ''
if exclude and 'org_id' in exclude:
exclude.remove('org_id')
unique_checks, date_checks = self._get_unique_checks(exclude=exclude)
errors = self._perform_unique_checks(unique_checks)
date_errors = self._perform_date_checks(date_checks)
for k, v in date_errors.items():
errors.setdefault(k, []).extend(v)
if errors:
raise ValidationError(errors)
2018-07-12 16:00:35 +00:00
class Meta:
abstract = True
2018-07-13 07:05:46 +00:00
class OrgViewGenericMixin:
def dispatch(self, request, *args, **kwargs):
print("Current org: {}".format(current_org))
2018-07-13 07:05:46 +00:00
if not current_org:
return redirect('orgs:switch-a-org')
if not current_org.can_admin_by(request.user):
print("{} cannot admin {}".format(request.user, current_org))
if request.user.is_org_admin:
print("Is org admin")
return redirect('orgs:switch-a-org')
return HttpResponseForbidden()
else:
print(current_org.can_admin_by(request.user))
2018-07-13 07:05:46 +00:00
return super().dispatch(request, *args, **kwargs)
2018-07-14 16:55:05 +00:00
2018-07-27 08:21:55 +00:00
class RootOrgViewMixin:
def dispatch(self, request, *args, **kwargs):
set_to_root_org()
return super().dispatch(request, *args, **kwargs)
2018-07-14 16:55:05 +00:00
class OrgModelForm(ModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# if 'initial' not in kwargs:
# return
2018-07-14 16:55:05 +00:00
for name, field in self.fields.items():
if not hasattr(field, 'queryset'):
continue
model = field.queryset.model
field.queryset = model.objects.all()