jumpserver/apps/common/models.py

82 lines
2.6 KiB
Python
Raw Normal View History

2018-01-11 12:10:27 +00:00
import json
2018-01-12 07:43:26 +00:00
import ldap
2016-09-03 11:05:50 +00:00
from django.db import models
2018-01-22 03:38:40 +00:00
from django.db.utils import ProgrammingError, OperationalError
2018-01-11 12:10:27 +00:00
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
2018-01-12 07:43:26 +00:00
from django_auth_ldap.config import LDAPSearch
2018-01-11 12:10:27 +00:00
class SettingQuerySet(models.QuerySet):
def __getattr__(self, item):
instances = self.filter(name=item)
if len(instances) == 1:
return instances[0]
else:
return Setting()
class SettingManager(models.Manager):
def get_queryset(self):
return SettingQuerySet(self.model, using=self._db)
class Setting(models.Model):
name = models.CharField(max_length=128, unique=True, verbose_name=_("Name"))
value = models.TextField(verbose_name=_("Value"))
2018-01-20 14:22:09 +00:00
category = models.CharField(max_length=128, default="default")
2018-01-11 12:10:27 +00:00
enabled = models.BooleanField(verbose_name=_("Enabled"), default=True)
comment = models.TextField(verbose_name=_("Comment"))
objects = SettingManager()
def __str__(self):
return self.name
2018-01-12 07:43:26 +00:00
@property
2018-01-20 14:22:09 +00:00
def cleaned_value(self):
2018-01-12 07:43:26 +00:00
try:
return json.loads(self.value)
except json.JSONDecodeError:
return None
2018-01-20 14:22:09 +00:00
@cleaned_value.setter
def cleaned_value(self, item):
try:
v = json.dumps(item)
self.value = v
except json.JSONDecodeError as e:
raise ValueError("Json dump error: {}".format(str(e)))
2018-01-11 12:10:27 +00:00
@classmethod
def refresh_all_settings(cls):
2018-01-22 03:38:40 +00:00
try:
settings_list = cls.objects.all()
for setting in settings_list:
setting.refresh_setting()
except (ProgrammingError, OperationalError):
pass
2018-01-11 12:10:27 +00:00
def refresh_setting(self):
try:
value = json.loads(self.value)
except json.JSONDecodeError:
return
setattr(settings, self.name, value)
2016-09-03 11:05:50 +00:00
2018-01-12 07:43:26 +00:00
if self.name == "AUTH_LDAP":
2018-01-20 14:22:09 +00:00
if self.cleaned_value and settings.AUTH_LDAP_BACKEND not in settings.AUTHENTICATION_BACKENDS:
2018-01-12 07:43:26 +00:00
settings.AUTHENTICATION_BACKENDS.insert(0, settings.AUTH_LDAP_BACKEND)
2018-01-20 14:22:09 +00:00
elif not self.cleaned_value and settings.AUTH_LDAP_BACKEND in settings.AUTHENTICATION_BACKENDS:
2018-01-12 07:43:26 +00:00
settings.AUTHENTICATION_BACKENDS.remove(settings.AUTH_LDAP_BACKEND)
if self.name == "AUTH_LDAP_SEARCH_FILTER":
settings.AUTH_LDAP_USER_SEARCH = LDAPSearch(
settings.AUTH_LDAP_SEARCH_OU, ldap.SCOPE_SUBTREE,
settings.AUTH_LDAP_SEARCH_FILTER,
)
2018-01-11 12:10:27 +00:00
class Meta:
db_table = "settings"