2019-03-11 02:06:45 +00:00
|
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
|
#
|
2022-11-11 07:04:31 +00:00
|
|
|
|
|
2023-04-26 11:11:53 +00:00
|
|
|
|
import ipaddress
|
2023-04-25 08:25:00 +00:00
|
|
|
|
import json
|
2023-05-18 05:14:32 +00:00
|
|
|
|
import logging
|
2023-05-12 11:16:55 +00:00
|
|
|
|
import re
|
2023-04-25 08:25:00 +00:00
|
|
|
|
|
|
|
|
|
from django.apps import apps
|
|
|
|
|
from django.core.exceptions import ValidationError
|
2022-11-11 09:28:13 +00:00
|
|
|
|
from django.core.validators import MinValueValidator, MaxValueValidator
|
2019-03-11 02:06:45 +00:00
|
|
|
|
from django.db import models
|
2023-06-08 10:33:43 +00:00
|
|
|
|
from django.db.models import Q, Manager, QuerySet
|
2023-07-24 03:52:25 +00:00
|
|
|
|
from django.utils.translation import gettext_lazy as _
|
2023-02-19 07:10:10 +00:00
|
|
|
|
from rest_framework.utils.encoders import JSONEncoder
|
2022-11-11 07:04:31 +00:00
|
|
|
|
|
2022-11-04 06:22:38 +00:00
|
|
|
|
from common.local import add_encrypted_field_set
|
2023-07-31 09:39:30 +00:00
|
|
|
|
from common.utils import contains_ip
|
|
|
|
|
from .utils import Encryptor
|
2023-01-16 11:02:09 +00:00
|
|
|
|
from .validators import PortRangeValidator
|
2019-03-11 02:06:45 +00:00
|
|
|
|
|
|
|
|
|
__all__ = [
|
2022-11-11 07:11:10 +00:00
|
|
|
|
"JsonMixin",
|
|
|
|
|
"JsonDictMixin",
|
|
|
|
|
"JsonListMixin",
|
|
|
|
|
"JsonTypeMixin",
|
|
|
|
|
"JsonCharField",
|
|
|
|
|
"JsonTextField",
|
|
|
|
|
"JsonListCharField",
|
|
|
|
|
"JsonListTextField",
|
|
|
|
|
"JsonDictCharField",
|
|
|
|
|
"JsonDictTextField",
|
|
|
|
|
"EncryptCharField",
|
|
|
|
|
"EncryptTextField",
|
|
|
|
|
"EncryptMixin",
|
|
|
|
|
"EncryptJsonDictTextField",
|
|
|
|
|
"EncryptJsonDictCharField",
|
|
|
|
|
"PortField",
|
2023-01-16 11:02:09 +00:00
|
|
|
|
"PortRangeField",
|
2022-11-11 07:11:10 +00:00
|
|
|
|
"BitChoices",
|
2023-01-16 11:02:09 +00:00
|
|
|
|
"TreeChoices",
|
2023-04-23 08:15:27 +00:00
|
|
|
|
"JSONManyToManyField",
|
2019-03-11 02:06:45 +00:00
|
|
|
|
]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class JsonMixin:
|
|
|
|
|
tp = None
|
|
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
|
def json_decode(data):
|
|
|
|
|
try:
|
|
|
|
|
return json.loads(data)
|
|
|
|
|
except (TypeError, json.JSONDecodeError):
|
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
|
def json_encode(data):
|
2023-02-19 07:10:10 +00:00
|
|
|
|
return json.dumps(data, cls=JSONEncoder)
|
2019-03-11 02:06:45 +00:00
|
|
|
|
|
2020-11-19 07:50:31 +00:00
|
|
|
|
def from_db_value(self, value, expression, connection, context=None):
|
2019-03-11 02:06:45 +00:00
|
|
|
|
if value is None:
|
|
|
|
|
return value
|
|
|
|
|
return self.json_decode(value)
|
|
|
|
|
|
|
|
|
|
def to_python(self, value):
|
|
|
|
|
if value is None:
|
|
|
|
|
return value
|
|
|
|
|
|
|
|
|
|
if not isinstance(value, str) or not value.startswith('"'):
|
|
|
|
|
return value
|
|
|
|
|
else:
|
|
|
|
|
return self.json_decode(value)
|
|
|
|
|
|
|
|
|
|
def get_prep_value(self, value):
|
|
|
|
|
if value is None:
|
|
|
|
|
return value
|
|
|
|
|
return self.json_encode(value)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class JsonTypeMixin(JsonMixin):
|
|
|
|
|
tp = dict
|
|
|
|
|
|
2020-11-19 07:50:31 +00:00
|
|
|
|
def from_db_value(self, value, expression, connection, context=None):
|
2019-03-11 02:06:45 +00:00
|
|
|
|
value = super().from_db_value(value, expression, connection, context)
|
|
|
|
|
if not isinstance(value, self.tp):
|
|
|
|
|
value = self.tp()
|
|
|
|
|
return value
|
|
|
|
|
|
|
|
|
|
def to_python(self, value):
|
|
|
|
|
data = super().to_python(value)
|
|
|
|
|
if not isinstance(data, self.tp):
|
|
|
|
|
data = self.tp()
|
|
|
|
|
return data
|
|
|
|
|
|
|
|
|
|
def get_prep_value(self, value):
|
|
|
|
|
if not isinstance(value, self.tp):
|
|
|
|
|
value = self.tp()
|
|
|
|
|
return self.json_encode(value)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class JsonDictMixin(JsonTypeMixin):
|
|
|
|
|
tp = dict
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class JsonDictCharField(JsonDictMixin, models.CharField):
|
|
|
|
|
description = _("Marshal dict data to char field")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class JsonDictTextField(JsonDictMixin, models.TextField):
|
|
|
|
|
description = _("Marshal dict data to text field")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class JsonListMixin(JsonTypeMixin):
|
|
|
|
|
tp = list
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class JsonStrListMixin(JsonListMixin):
|
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class JsonListCharField(JsonListMixin, models.CharField):
|
|
|
|
|
description = _("Marshal list data to char field")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class JsonListTextField(JsonListMixin, models.TextField):
|
|
|
|
|
description = _("Marshal list data to text field")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class JsonCharField(JsonMixin, models.CharField):
|
|
|
|
|
description = _("Marshal data to char field")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class JsonTextField(JsonMixin, models.TextField):
|
|
|
|
|
description = _("Marshal data to text field")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class EncryptMixin:
|
2019-12-18 07:37:53 +00:00
|
|
|
|
"""
|
|
|
|
|
EncryptMixin要放在最前面
|
|
|
|
|
"""
|
2020-06-11 06:10:55 +00:00
|
|
|
|
|
2020-11-19 07:50:31 +00:00
|
|
|
|
def from_db_value(self, value, expression, connection, context=None):
|
2022-12-05 10:54:12 +00:00
|
|
|
|
if value is None:
|
2019-12-18 07:37:53 +00:00
|
|
|
|
return value
|
2020-06-11 04:10:00 +00:00
|
|
|
|
|
2023-07-31 09:39:30 +00:00
|
|
|
|
plain_value = Encryptor(value).decrypt()
|
2020-06-11 06:10:55 +00:00
|
|
|
|
# 可能和Json mix,所以要先解密,再json
|
2019-12-18 07:37:53 +00:00
|
|
|
|
sp = super()
|
2022-11-11 07:11:10 +00:00
|
|
|
|
if hasattr(sp, "from_db_value"):
|
2020-06-11 04:10:00 +00:00
|
|
|
|
plain_value = sp.from_db_value(plain_value, expression, connection, context)
|
|
|
|
|
return plain_value
|
2019-03-11 02:06:45 +00:00
|
|
|
|
|
|
|
|
|
def get_prep_value(self, value):
|
2022-12-05 10:54:12 +00:00
|
|
|
|
if value is None:
|
2019-03-11 02:06:45 +00:00
|
|
|
|
return value
|
2020-06-11 06:10:55 +00:00
|
|
|
|
|
|
|
|
|
# 先 json 再解密
|
2019-12-18 07:37:53 +00:00
|
|
|
|
sp = super()
|
2022-11-11 07:11:10 +00:00
|
|
|
|
if hasattr(sp, "get_prep_value"):
|
2019-12-18 07:37:53 +00:00
|
|
|
|
value = sp.get_prep_value(value)
|
2023-07-31 09:39:30 +00:00
|
|
|
|
|
2020-06-11 04:10:00 +00:00
|
|
|
|
# 替换新的加密方式
|
2023-07-31 09:39:30 +00:00
|
|
|
|
return Encryptor(value).encrypt()
|
2019-03-11 02:06:45 +00:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class EncryptTextField(EncryptMixin, models.TextField):
|
|
|
|
|
description = _("Encrypt field using Secret Key")
|
|
|
|
|
|
2022-11-04 06:22:38 +00:00
|
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
|
super().__init__(*args, **kwargs)
|
|
|
|
|
add_encrypted_field_set(self.verbose_name)
|
|
|
|
|
|
2019-03-11 02:06:45 +00:00
|
|
|
|
|
|
|
|
|
class EncryptCharField(EncryptMixin, models.CharField):
|
2019-06-24 14:16:39 +00:00
|
|
|
|
@staticmethod
|
|
|
|
|
def change_max_length(kwargs):
|
2022-11-11 07:11:10 +00:00
|
|
|
|
kwargs.setdefault("max_length", 1024)
|
|
|
|
|
max_length = kwargs.get("max_length")
|
2019-06-24 14:16:39 +00:00
|
|
|
|
if max_length < 129:
|
|
|
|
|
max_length = 128
|
|
|
|
|
max_length = max_length * 2
|
2022-11-11 07:11:10 +00:00
|
|
|
|
kwargs["max_length"] = max_length
|
2019-06-24 14:16:39 +00:00
|
|
|
|
|
2019-03-11 02:06:45 +00:00
|
|
|
|
def __init__(self, *args, **kwargs):
|
2019-06-24 14:16:39 +00:00
|
|
|
|
self.change_max_length(kwargs)
|
2019-03-11 02:06:45 +00:00
|
|
|
|
super().__init__(*args, **kwargs)
|
2022-11-04 06:22:38 +00:00
|
|
|
|
add_encrypted_field_set(self.verbose_name)
|
2019-03-11 02:06:45 +00:00
|
|
|
|
|
2019-06-24 14:16:39 +00:00
|
|
|
|
def deconstruct(self):
|
|
|
|
|
name, path, args, kwargs = super().deconstruct()
|
2022-11-11 07:11:10 +00:00
|
|
|
|
max_length = kwargs.pop("max_length")
|
2019-06-24 14:16:39 +00:00
|
|
|
|
if max_length > 255:
|
|
|
|
|
max_length = max_length // 2
|
2022-11-11 07:11:10 +00:00
|
|
|
|
kwargs["max_length"] = max_length
|
2019-06-24 14:16:39 +00:00
|
|
|
|
return name, path, args, kwargs
|
|
|
|
|
|
2019-03-11 02:06:45 +00:00
|
|
|
|
|
2019-05-20 11:39:53 +00:00
|
|
|
|
class EncryptJsonDictTextField(EncryptMixin, JsonDictTextField):
|
2022-11-04 06:22:38 +00:00
|
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
|
super().__init__(*args, **kwargs)
|
|
|
|
|
add_encrypted_field_set(self.verbose_name)
|
2019-05-20 11:39:53 +00:00
|
|
|
|
|
2019-03-11 02:06:45 +00:00
|
|
|
|
|
2019-12-18 07:37:53 +00:00
|
|
|
|
class EncryptJsonDictCharField(EncryptMixin, JsonDictCharField):
|
2022-11-04 06:22:38 +00:00
|
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
|
super().__init__(*args, **kwargs)
|
|
|
|
|
add_encrypted_field_set(self.verbose_name)
|
2019-12-18 07:37:53 +00:00
|
|
|
|
|
2022-04-12 09:45:10 +00:00
|
|
|
|
|
|
|
|
|
class PortField(models.IntegerField):
|
|
|
|
|
def __init__(self, *args, **kwargs):
|
2022-11-11 07:11:10 +00:00
|
|
|
|
kwargs.update(
|
|
|
|
|
{
|
|
|
|
|
"blank": False,
|
|
|
|
|
"null": False,
|
|
|
|
|
"validators": [MinValueValidator(0), MaxValueValidator(65535)],
|
|
|
|
|
}
|
|
|
|
|
)
|
2022-04-12 09:45:10 +00:00
|
|
|
|
super().__init__(*args, **kwargs)
|
|
|
|
|
|
2022-11-11 07:04:31 +00:00
|
|
|
|
|
2023-01-16 11:02:09 +00:00
|
|
|
|
class TreeChoices(models.Choices):
|
2022-11-11 07:04:31 +00:00
|
|
|
|
@classmethod
|
2023-01-16 11:02:09 +00:00
|
|
|
|
def is_tree(cls):
|
|
|
|
|
return True
|
2022-11-11 07:04:31 +00:00
|
|
|
|
|
2022-11-11 09:28:13 +00:00
|
|
|
|
@classmethod
|
2023-01-16 11:02:09 +00:00
|
|
|
|
def branches(cls):
|
|
|
|
|
return [i for i in cls]
|
2022-11-11 09:28:13 +00:00
|
|
|
|
|
2022-11-11 07:04:31 +00:00
|
|
|
|
@classmethod
|
|
|
|
|
def tree(cls):
|
2022-11-11 09:28:13 +00:00
|
|
|
|
if not cls.is_tree():
|
|
|
|
|
return []
|
2022-11-11 07:11:10 +00:00
|
|
|
|
root = [_("All"), cls.branches()]
|
2022-11-11 09:28:13 +00:00
|
|
|
|
return [cls.render_node(root)]
|
2022-11-11 07:04:31 +00:00
|
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
|
def render_node(cls, node):
|
2023-01-16 11:02:09 +00:00
|
|
|
|
if isinstance(node, models.Choices):
|
2022-11-11 07:04:31 +00:00
|
|
|
|
return {
|
2022-11-11 09:28:13 +00:00
|
|
|
|
"value": node.name,
|
2022-11-11 07:11:10 +00:00
|
|
|
|
"label": node.label,
|
2022-11-11 07:04:31 +00:00
|
|
|
|
}
|
|
|
|
|
else:
|
|
|
|
|
name, children = node
|
|
|
|
|
return {
|
2022-11-11 09:28:13 +00:00
|
|
|
|
"value": name,
|
2022-11-11 07:11:10 +00:00
|
|
|
|
"label": name,
|
|
|
|
|
"children": [cls.render_node(child) for child in children],
|
2022-11-11 07:04:31 +00:00
|
|
|
|
}
|
|
|
|
|
|
2023-01-16 11:02:09 +00:00
|
|
|
|
@classmethod
|
|
|
|
|
def all(cls):
|
|
|
|
|
return [i[0] for i in cls.choices]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class BitChoices(models.IntegerChoices, TreeChoices):
|
|
|
|
|
@classmethod
|
|
|
|
|
def is_tree(cls):
|
|
|
|
|
return False
|
|
|
|
|
|
2022-11-11 07:04:31 +00:00
|
|
|
|
@classmethod
|
|
|
|
|
def all(cls):
|
2023-11-08 09:46:32 +00:00
|
|
|
|
# 权限 12 位 最大值
|
|
|
|
|
return 4095
|
2023-01-16 11:02:09 +00:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class PortRangeField(models.CharField):
|
|
|
|
|
def __init__(self, **kwargs):
|
|
|
|
|
kwargs['max_length'] = 16
|
|
|
|
|
super().__init__(**kwargs)
|
|
|
|
|
self.validators.append(PortRangeValidator())
|
2023-04-23 08:15:27 +00:00
|
|
|
|
|
|
|
|
|
|
2023-04-24 08:27:13 +00:00
|
|
|
|
class RelatedManager:
|
|
|
|
|
def __init__(self, instance, field):
|
|
|
|
|
self.instance = instance
|
|
|
|
|
self.field = field
|
2023-04-24 11:00:31 +00:00
|
|
|
|
self.value = None
|
2023-04-24 08:27:13 +00:00
|
|
|
|
|
|
|
|
|
def set(self, value):
|
2023-04-24 11:00:31 +00:00
|
|
|
|
self.value = value
|
|
|
|
|
self.instance.__dict__[self.field.name] = value
|
2023-04-24 08:27:13 +00:00
|
|
|
|
|
2023-05-18 09:31:40 +00:00
|
|
|
|
@classmethod
|
2023-11-01 07:38:03 +00:00
|
|
|
|
def get_to_filter_qs(cls, value, to_model):
|
2023-06-14 10:17:20 +00:00
|
|
|
|
"""
|
|
|
|
|
这个是 instance 去查找 to_model 的 queryset 的 Q
|
|
|
|
|
:param value:
|
|
|
|
|
:param to_model:
|
|
|
|
|
:return:
|
|
|
|
|
"""
|
2023-11-01 07:38:03 +00:00
|
|
|
|
default = [Q()]
|
2023-05-18 09:31:40 +00:00
|
|
|
|
if not value or not isinstance(value, dict):
|
2023-11-01 07:38:03 +00:00
|
|
|
|
return default
|
2023-05-18 09:31:40 +00:00
|
|
|
|
|
|
|
|
|
if value["type"] == "all":
|
2023-11-01 07:38:03 +00:00
|
|
|
|
return default
|
2023-05-18 09:31:40 +00:00
|
|
|
|
elif value["type"] == "ids" and isinstance(value.get("ids"), list):
|
2023-11-01 07:38:03 +00:00
|
|
|
|
return [Q(id__in=value["ids"])]
|
2023-05-18 09:31:40 +00:00
|
|
|
|
elif value["type"] == "attrs" and isinstance(value.get("attrs"), list):
|
2023-11-01 07:38:03 +00:00
|
|
|
|
return cls._get_filter_attrs_qs(value, to_model)
|
2023-05-18 09:31:40 +00:00
|
|
|
|
else:
|
2023-11-01 07:38:03 +00:00
|
|
|
|
return default
|
2023-05-18 09:31:40 +00:00
|
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
|
def filter_queryset_by_model(cls, value, to_model):
|
|
|
|
|
if hasattr(to_model, "get_queryset"):
|
|
|
|
|
queryset = to_model.get_queryset()
|
|
|
|
|
else:
|
|
|
|
|
queryset = to_model.objects.all()
|
2023-11-01 07:38:03 +00:00
|
|
|
|
qs = cls.get_to_filter_qs(value, to_model)
|
|
|
|
|
for q in qs:
|
|
|
|
|
queryset = queryset.filter(q)
|
|
|
|
|
return queryset.distinct()
|
2023-05-18 09:31:40 +00:00
|
|
|
|
|
2023-04-26 11:11:53 +00:00
|
|
|
|
@staticmethod
|
|
|
|
|
def get_ip_in_q(name, val):
|
|
|
|
|
q = Q()
|
|
|
|
|
if isinstance(val, str):
|
|
|
|
|
val = [val]
|
2023-06-15 10:13:51 +00:00
|
|
|
|
if ['*'] in val:
|
|
|
|
|
return Q()
|
2023-04-26 11:11:53 +00:00
|
|
|
|
for ip in val:
|
|
|
|
|
if not ip:
|
|
|
|
|
continue
|
|
|
|
|
try:
|
2023-06-15 10:13:51 +00:00
|
|
|
|
if '/' in ip:
|
2023-04-26 11:11:53 +00:00
|
|
|
|
network = ipaddress.ip_network(ip)
|
|
|
|
|
ips = network.hosts()
|
|
|
|
|
q |= Q(**{"{}__in".format(name): ips})
|
|
|
|
|
elif '-' in ip:
|
|
|
|
|
start_ip, end_ip = ip.split('-')
|
|
|
|
|
start_ip = ipaddress.ip_address(start_ip)
|
|
|
|
|
end_ip = ipaddress.ip_address(end_ip)
|
|
|
|
|
q |= Q(**{"{}__range".format(name): (start_ip, end_ip)})
|
|
|
|
|
elif len(ip.split('.')) == 4:
|
|
|
|
|
q |= Q(**{"{}__exact".format(name): ip})
|
|
|
|
|
else:
|
|
|
|
|
q |= Q(**{"{}__startswith".format(name): ip})
|
|
|
|
|
except ValueError:
|
|
|
|
|
continue
|
|
|
|
|
return q
|
|
|
|
|
|
2023-05-18 09:31:40 +00:00
|
|
|
|
@classmethod
|
2023-11-01 07:38:03 +00:00
|
|
|
|
def _get_filter_attrs_qs(cls, value, to_model):
|
|
|
|
|
filters = []
|
2023-05-18 05:14:32 +00:00
|
|
|
|
# 特殊情况有这几种,
|
|
|
|
|
# 1. 像 资产中的 type 和 category,集成自 Platform。所以不能直接查询
|
|
|
|
|
# 2. 像 资产中的 nodes,不是简单的 m2m,是树 的关系
|
|
|
|
|
# 3. 像 用户中的 orgs 也不是简单的 m2m,也是计算出来的
|
|
|
|
|
# get_filter_{}_attr_q 处理复杂的
|
|
|
|
|
custom_attr_filter = getattr(to_model, "get_json_filter_attr_q", None)
|
|
|
|
|
for attr in value["attrs"]:
|
|
|
|
|
if not isinstance(attr, dict):
|
|
|
|
|
continue
|
2023-04-24 08:27:13 +00:00
|
|
|
|
|
2023-05-18 05:14:32 +00:00
|
|
|
|
name = attr.get('name')
|
|
|
|
|
val = attr.get('value')
|
|
|
|
|
match = attr.get('match', 'exact')
|
|
|
|
|
if name is None or val is None:
|
|
|
|
|
continue
|
2023-04-26 11:11:53 +00:00
|
|
|
|
|
2024-01-22 03:36:18 +00:00
|
|
|
|
custom_filter_q = None
|
|
|
|
|
spec_attr_filter = getattr(to_model, "get_{}_filter_attr_q".format(name), None)
|
|
|
|
|
if spec_attr_filter:
|
|
|
|
|
custom_filter_q = spec_attr_filter(val, match)
|
|
|
|
|
elif custom_attr_filter:
|
2023-05-18 05:14:32 +00:00
|
|
|
|
custom_filter_q = custom_attr_filter(name, val, match)
|
2024-01-22 03:36:18 +00:00
|
|
|
|
if custom_filter_q:
|
|
|
|
|
filters.append(custom_filter_q)
|
|
|
|
|
continue
|
2023-04-25 08:25:00 +00:00
|
|
|
|
|
2023-05-18 05:14:32 +00:00
|
|
|
|
if match == 'ip_in':
|
2023-05-18 09:31:40 +00:00
|
|
|
|
q = cls.get_ip_in_q(name, val)
|
2023-06-15 10:13:51 +00:00
|
|
|
|
elif match in ("contains", "startswith", "endswith", "gte", "lte", "gt", "lt"):
|
2023-05-18 05:14:32 +00:00
|
|
|
|
lookup = "{}__{}".format(name, match)
|
|
|
|
|
q = Q(**{lookup: val})
|
2023-06-15 02:27:52 +00:00
|
|
|
|
elif match == 'regex':
|
|
|
|
|
try:
|
|
|
|
|
re.compile(val)
|
|
|
|
|
lookup = "{}__{}".format(name, match)
|
|
|
|
|
q = Q(**{lookup: val})
|
|
|
|
|
except re.error:
|
2023-07-20 06:46:56 +00:00
|
|
|
|
q = Q(pk__isnull=True)
|
2023-05-18 05:14:32 +00:00
|
|
|
|
elif match == "not":
|
|
|
|
|
q = ~Q(**{name: val})
|
2023-11-01 07:38:03 +00:00
|
|
|
|
elif match.startswith('m2m'):
|
|
|
|
|
if not isinstance(val, list):
|
|
|
|
|
val = [val]
|
|
|
|
|
if match == 'm2m_all':
|
|
|
|
|
for v in val:
|
|
|
|
|
filters.append(Q(**{"{}__in".format(name): [v]}))
|
|
|
|
|
continue
|
|
|
|
|
else:
|
|
|
|
|
q = Q(**{"{}__in".format(name): val})
|
|
|
|
|
elif match == 'in':
|
2023-05-18 05:14:32 +00:00
|
|
|
|
if not isinstance(val, list):
|
|
|
|
|
val = [val]
|
2023-05-19 03:30:50 +00:00
|
|
|
|
q = Q() if '*' in val else Q(**{"{}__in".format(name): val})
|
2023-05-18 05:14:32 +00:00
|
|
|
|
else:
|
2023-05-19 03:30:50 +00:00
|
|
|
|
q = Q() if val == '*' else Q(**{name: val})
|
2023-11-01 07:38:03 +00:00
|
|
|
|
filters.append(q)
|
2023-05-18 05:14:32 +00:00
|
|
|
|
return filters
|
|
|
|
|
|
|
|
|
|
def _get_queryset(self):
|
|
|
|
|
to_model = apps.get_model(self.field.to)
|
|
|
|
|
value = self.value
|
2023-05-18 09:31:40 +00:00
|
|
|
|
return self.filter_queryset_by_model(value, to_model)
|
2023-05-18 05:14:32 +00:00
|
|
|
|
|
|
|
|
|
def get_attr_q(self):
|
2023-06-12 08:00:14 +00:00
|
|
|
|
to_model = apps.get_model(self.field.to)
|
2023-11-01 07:38:03 +00:00
|
|
|
|
qs = self._get_filter_attrs_qs(self.value, to_model)
|
|
|
|
|
return qs
|
2023-04-24 08:27:13 +00:00
|
|
|
|
|
|
|
|
|
def all(self):
|
|
|
|
|
return self._get_queryset()
|
|
|
|
|
|
|
|
|
|
def filter(self, *args, **kwargs):
|
|
|
|
|
queryset = self._get_queryset()
|
|
|
|
|
return queryset.filter(*args, **kwargs)
|
|
|
|
|
|
|
|
|
|
|
2023-04-23 08:15:27 +00:00
|
|
|
|
class JSONManyToManyDescriptor:
|
|
|
|
|
def __init__(self, field):
|
|
|
|
|
self.field = field
|
|
|
|
|
self._is_setting = False
|
|
|
|
|
|
|
|
|
|
def __get__(self, instance, owner=None):
|
|
|
|
|
if instance is None:
|
|
|
|
|
return self
|
|
|
|
|
|
|
|
|
|
if not hasattr(instance, "_related_manager_cache"):
|
|
|
|
|
instance._related_manager_cache = {}
|
2023-04-24 08:27:13 +00:00
|
|
|
|
if self.field.name not in instance._related_manager_cache:
|
2023-04-23 08:15:27 +00:00
|
|
|
|
manager = RelatedManager(instance, self.field)
|
|
|
|
|
instance._related_manager_cache[self.field.name] = manager
|
2023-04-24 11:00:31 +00:00
|
|
|
|
manager = instance._related_manager_cache[self.field.name]
|
|
|
|
|
return manager
|
2023-04-23 08:15:27 +00:00
|
|
|
|
|
|
|
|
|
def __set__(self, instance, value):
|
|
|
|
|
if instance is None:
|
|
|
|
|
return
|
|
|
|
|
|
2023-04-24 08:27:13 +00:00
|
|
|
|
if not hasattr(instance, "_related_manager_cache"):
|
|
|
|
|
instance._related_manager_cache = {}
|
2023-04-23 08:15:27 +00:00
|
|
|
|
|
2023-04-24 08:27:13 +00:00
|
|
|
|
if self.field.name not in instance._related_manager_cache:
|
2023-04-23 08:15:27 +00:00
|
|
|
|
manager = self.__get__(instance, instance.__class__)
|
2023-04-24 08:27:13 +00:00
|
|
|
|
else:
|
|
|
|
|
manager = instance._related_manager_cache[self.field.name]
|
|
|
|
|
|
|
|
|
|
if isinstance(value, RelatedManager):
|
2023-04-24 11:00:31 +00:00
|
|
|
|
value = value.value
|
2023-04-24 08:27:13 +00:00
|
|
|
|
manager.set(value)
|
2023-04-23 08:15:27 +00:00
|
|
|
|
|
2023-05-18 05:14:32 +00:00
|
|
|
|
def is_match(self, obj, attr_rules):
|
|
|
|
|
# m2m 的情况
|
|
|
|
|
# 自定义的情况:比如 nodes, category
|
|
|
|
|
res = True
|
|
|
|
|
to_model = apps.get_model(self.field.to)
|
2023-06-13 05:48:32 +00:00
|
|
|
|
custom_attr_filter = getattr(to_model, "get_json_filter_attr_q", None)
|
2023-05-12 11:16:55 +00:00
|
|
|
|
|
2023-05-18 05:14:32 +00:00
|
|
|
|
custom_q = Q()
|
2023-05-12 11:16:55 +00:00
|
|
|
|
for rule in attr_rules:
|
2023-07-17 07:05:20 +00:00
|
|
|
|
value = getattr(obj, rule['name'], None) or ''
|
2023-05-18 05:14:32 +00:00
|
|
|
|
rule_value = rule.get('value', '')
|
|
|
|
|
rule_match = rule.get('match', 'exact')
|
|
|
|
|
|
2024-01-22 03:36:18 +00:00
|
|
|
|
custom_filter_q = None
|
|
|
|
|
spec_attr_filter = getattr(to_model, "get_filter_{}_attr_q".format(rule['name']), None)
|
|
|
|
|
if spec_attr_filter:
|
|
|
|
|
custom_filter_q = spec_attr_filter(rule_value, rule_match)
|
|
|
|
|
elif custom_attr_filter:
|
|
|
|
|
custom_filter_q = custom_attr_filter(rule['name'], rule_value, rule_match)
|
|
|
|
|
if custom_filter_q:
|
|
|
|
|
custom_q &= custom_filter_q
|
|
|
|
|
continue
|
2023-05-18 05:14:32 +00:00
|
|
|
|
|
|
|
|
|
if rule_match == 'in':
|
2023-06-15 10:13:51 +00:00
|
|
|
|
res &= value in rule_value or '*' in rule_value
|
2023-05-18 05:14:32 +00:00
|
|
|
|
elif rule_match == 'exact':
|
2023-06-15 10:13:51 +00:00
|
|
|
|
res &= value == rule_value or rule_value == '*'
|
2023-05-18 05:14:32 +00:00
|
|
|
|
elif rule_match == 'contains':
|
2023-07-17 07:05:20 +00:00
|
|
|
|
res &= (rule_value in value)
|
2023-05-18 05:14:32 +00:00
|
|
|
|
elif rule_match == 'startswith':
|
|
|
|
|
res &= str(value).startswith(str(rule_value))
|
|
|
|
|
elif rule_match == 'endswith':
|
|
|
|
|
res &= str(value).endswith(str(rule_value))
|
|
|
|
|
elif rule_match == 'regex':
|
2023-06-09 10:32:56 +00:00
|
|
|
|
try:
|
2023-06-14 12:39:03 +00:00
|
|
|
|
matched = bool(re.search(r'{}'.format(rule_value), value))
|
2023-06-09 10:32:56 +00:00
|
|
|
|
except Exception as e:
|
|
|
|
|
logging.error('Error regex match: %s', e)
|
|
|
|
|
matched = False
|
|
|
|
|
res &= matched
|
2023-05-18 05:14:32 +00:00
|
|
|
|
elif rule_match == 'not':
|
|
|
|
|
res &= value != rule_value
|
|
|
|
|
elif rule['match'] == 'gte':
|
|
|
|
|
res &= value >= rule_value
|
|
|
|
|
elif rule['match'] == 'lte':
|
|
|
|
|
res &= value <= rule_value
|
|
|
|
|
elif rule['match'] == 'gt':
|
|
|
|
|
res &= value > rule_value
|
|
|
|
|
elif rule['match'] == 'lt':
|
|
|
|
|
res &= value < rule_value
|
|
|
|
|
elif rule['match'] == 'ip_in':
|
|
|
|
|
if isinstance(rule_value, str):
|
|
|
|
|
rule_value = [rule_value]
|
2023-06-15 10:13:51 +00:00
|
|
|
|
res &= '*' in rule_value or contains_ip(value, rule_value)
|
2023-11-01 07:38:03 +00:00
|
|
|
|
elif rule['match'].startswith('m2m'):
|
2023-05-18 05:14:32 +00:00
|
|
|
|
if isinstance(value, Manager):
|
|
|
|
|
value = value.values_list('id', flat=True)
|
2023-06-08 10:33:43 +00:00
|
|
|
|
elif isinstance(value, QuerySet):
|
|
|
|
|
value = value.values_list('id', flat=True)
|
|
|
|
|
elif isinstance(value, models.Model):
|
|
|
|
|
value = [value.id]
|
2023-06-15 02:16:18 +00:00
|
|
|
|
if isinstance(rule_value, (str, int)):
|
|
|
|
|
rule_value = [rule_value]
|
2023-05-18 05:14:32 +00:00
|
|
|
|
value = set(map(str, value))
|
|
|
|
|
rule_value = set(map(str, rule_value))
|
2023-11-01 07:38:03 +00:00
|
|
|
|
|
|
|
|
|
if rule['match'] == 'm2m_all':
|
|
|
|
|
res &= rule_value.issubset(value)
|
|
|
|
|
else:
|
|
|
|
|
res &= bool(value & rule_value)
|
2023-05-18 05:14:32 +00:00
|
|
|
|
else:
|
|
|
|
|
logging.error("unknown match: {}".format(rule['match']))
|
|
|
|
|
res &= False
|
|
|
|
|
|
|
|
|
|
if not res:
|
|
|
|
|
return res
|
|
|
|
|
if custom_q:
|
|
|
|
|
res &= to_model.objects.filter(custom_q).filter(id=obj.id).exists()
|
|
|
|
|
return res
|
2023-05-12 11:16:55 +00:00
|
|
|
|
|
|
|
|
|
def get_filter_q(self, instance):
|
2023-06-13 05:48:32 +00:00
|
|
|
|
"""
|
|
|
|
|
这个是某个 instance 获取 关联 资源的 filter q
|
|
|
|
|
:param instance:
|
|
|
|
|
:return:
|
|
|
|
|
"""
|
2023-05-12 11:16:55 +00:00
|
|
|
|
model_cls = self.field.model
|
|
|
|
|
field_name = self.field.column
|
2023-05-25 03:42:39 +00:00
|
|
|
|
q = Q(**{f'{field_name}__type': 'all'}) | \
|
2023-06-13 05:48:32 +00:00
|
|
|
|
Q(**{
|
|
|
|
|
f'{field_name}__type': 'ids',
|
|
|
|
|
f'{field_name}__ids__contains': [str(instance.id)]
|
|
|
|
|
})
|
2023-05-12 11:16:55 +00:00
|
|
|
|
queryset_id_attrs = model_cls.objects \
|
|
|
|
|
.filter(**{'{}__type'.format(field_name): 'attrs'}) \
|
|
|
|
|
.values_list('id', '{}__attrs'.format(field_name))
|
2023-06-13 05:48:32 +00:00
|
|
|
|
ids = [str(_id) for _id, attr_rules in queryset_id_attrs
|
|
|
|
|
if self.is_match(instance, attr_rules)]
|
2023-05-12 11:16:55 +00:00
|
|
|
|
if ids:
|
|
|
|
|
q |= Q(id__in=ids)
|
|
|
|
|
return q
|
|
|
|
|
|
|
|
|
|
|
2023-04-23 08:15:27 +00:00
|
|
|
|
class JSONManyToManyField(models.JSONField):
|
2023-04-24 08:27:13 +00:00
|
|
|
|
def __init__(self, to, *args, **kwargs):
|
|
|
|
|
self.to = to
|
2023-04-23 08:15:27 +00:00
|
|
|
|
super().__init__(*args, **kwargs)
|
|
|
|
|
|
|
|
|
|
def contribute_to_class(self, cls, name, **kwargs):
|
|
|
|
|
super().contribute_to_class(cls, name, **kwargs)
|
|
|
|
|
setattr(cls, self.name, JSONManyToManyDescriptor(self))
|
|
|
|
|
|
|
|
|
|
def deconstruct(self):
|
|
|
|
|
name, path, args, kwargs = super().deconstruct()
|
2023-04-24 08:27:13 +00:00
|
|
|
|
kwargs['to'] = self.to
|
2023-04-23 08:15:27 +00:00
|
|
|
|
return name, path, args, kwargs
|
|
|
|
|
|
2023-04-25 08:25:00 +00:00
|
|
|
|
@staticmethod
|
2023-04-27 06:13:40 +00:00
|
|
|
|
def check_value(val):
|
2023-04-25 08:25:00 +00:00
|
|
|
|
if not val:
|
|
|
|
|
return val
|
2023-04-27 06:13:40 +00:00
|
|
|
|
e = ValueError(_(
|
|
|
|
|
"Invalid JSON data for JSONManyToManyField, should be like "
|
|
|
|
|
"{'type': 'all'} or {'type': 'ids', 'ids': []} "
|
2023-05-18 05:14:32 +00:00
|
|
|
|
"or {'type': 'attrs', 'attrs': [{'name': 'ip', 'match': 'exact', 'value': '1.1.1.1'}}"
|
2023-04-27 06:13:40 +00:00
|
|
|
|
))
|
2023-04-25 08:25:00 +00:00
|
|
|
|
if not isinstance(val, dict):
|
|
|
|
|
raise e
|
|
|
|
|
if val["type"] not in ["all", "ids", "attrs"]:
|
2023-04-27 06:13:40 +00:00
|
|
|
|
raise ValueError(_('Invalid type, should be "all", "ids" or "attrs"'))
|
2023-04-25 08:25:00 +00:00
|
|
|
|
if val["type"] == "ids":
|
|
|
|
|
if not isinstance(val["ids"], list):
|
2023-04-27 06:13:40 +00:00
|
|
|
|
raise ValueError(_("Invalid ids for ids, should be a list"))
|
2023-06-12 02:25:14 +00:00
|
|
|
|
if not val["ids"]:
|
|
|
|
|
raise ValueError(_("This field is required."))
|
2023-04-25 08:25:00 +00:00
|
|
|
|
elif val["type"] == "attrs":
|
|
|
|
|
if not isinstance(val["attrs"], list):
|
2023-04-27 06:13:40 +00:00
|
|
|
|
raise ValueError(_("Invalid attrs, should be a list of dict"))
|
2023-06-12 02:25:14 +00:00
|
|
|
|
if not val["attrs"]:
|
|
|
|
|
raise ValueError(_("This field is required."))
|
2023-04-25 08:25:00 +00:00
|
|
|
|
for attr in val["attrs"]:
|
|
|
|
|
if not isinstance(attr, dict):
|
2023-04-27 06:13:40 +00:00
|
|
|
|
raise ValueError(_("Invalid attrs, should be a list of dict"))
|
2023-04-25 08:25:00 +00:00
|
|
|
|
if 'name' not in attr or 'value' not in attr:
|
2023-04-27 06:13:40 +00:00
|
|
|
|
raise ValueError(_("Invalid attrs, should be has name and value"))
|
2023-04-25 08:25:00 +00:00
|
|
|
|
|
2023-04-26 11:11:53 +00:00
|
|
|
|
def get_prep_value(self, value):
|
|
|
|
|
if value is None:
|
2023-04-24 08:27:13 +00:00
|
|
|
|
return None
|
2023-04-26 11:11:53 +00:00
|
|
|
|
if isinstance(value, RelatedManager):
|
|
|
|
|
value = value.value
|
|
|
|
|
return json.dumps(value)
|
2023-04-24 08:27:13 +00:00
|
|
|
|
|
2023-04-23 08:15:27 +00:00
|
|
|
|
def validate(self, value, model_instance):
|
|
|
|
|
super().validate(value, model_instance)
|
2023-04-24 08:27:13 +00:00
|
|
|
|
if not isinstance(value, dict):
|
2023-04-23 08:15:27 +00:00
|
|
|
|
raise ValidationError("Invalid JSON data for JSONManyToManyField.")
|
2023-05-12 11:16:55 +00:00
|
|
|
|
self.check_value(value)
|