authentik.api.search.fields
DjangoQL search
1"""DjangoQL search""" 2 3from collections import OrderedDict, defaultdict 4from collections.abc import Generator 5from decimal import Decimal 6 7from django.db import connection 8from django.db.models import Model, Q 9from djangoql.compat import text_type 10from djangoql.schema import StrField 11from djangoql.serializers import DjangoQLSchemaSerializer 12 13from authentik.lib.utils.db import distinct_values_containing 14 15 16class JSONSearchField(StrField): 17 """JSON field for DjangoQL""" 18 19 model: Model 20 21 value_types = [str, bool, int, float, Decimal] 22 value_types_description = "strings, booleans or numbers" 23 24 def get_lookup_value(self, value): 25 value = super().get_lookup_value(value) 26 if isinstance(value, list): 27 return [float(item) if isinstance(item, Decimal) else item for item in value] 28 if isinstance(value, Decimal): 29 return float(value) 30 return value 31 32 def __init__( 33 self, 34 model=None, 35 name=None, 36 nullable=None, 37 suggest_nested=False, 38 fixed_structure: OrderedDict | None = None, 39 ): 40 # Set this in the constructor to not clobber the type variable 41 self.type = "relation" 42 self.suggest_nested = suggest_nested 43 self.fixed_structure = fixed_structure 44 super().__init__(model, name, nullable) 45 46 def get_lookup(self, path, operator, value): 47 search = "__".join(path) 48 op, invert = self.get_operator(operator) 49 q = Q(**{f"{search}{op}": self.get_lookup_value(value)}) 50 return ~q if invert else q 51 52 def json_field_keys(self) -> Generator[tuple[str]]: 53 with connection.cursor() as cursor: 54 cursor.execute(f""" 55 WITH RECURSIVE "{self.name}_keys" AS ( 56 SELECT 57 ARRAY[jsonb_object_keys("{self.name}")] AS key_path_array, 58 "{self.name}" -> jsonb_object_keys("{self.name}") AS value 59 FROM {self.model._meta.db_table} 60 WHERE "{self.name}" IS NOT NULL 61 AND jsonb_typeof("{self.name}") = 'object' 62 63 UNION ALL 64 65 SELECT 66 ck.key_path_array || jsonb_object_keys(ck.value), 67 ck.value -> jsonb_object_keys(ck.value) AS value 68 FROM "{self.name}_keys" ck 69 WHERE jsonb_typeof(ck.value) = 'object' 70 ), 71 72 unique_paths AS ( 73 SELECT DISTINCT key_path_array 74 FROM "{self.name}_keys" 75 ) 76 77 SELECT key_path_array FROM unique_paths; 78 """) # nosec 79 return (x[0] for x in cursor.fetchall()) 80 81 def get_fixed_structure(self, serializer: DjangoQLSchemaSerializer) -> OrderedDict: 82 new_dict = OrderedDict() 83 if not self.fixed_structure: 84 return new_dict 85 new_dict.setdefault(self.relation(), {}) 86 for key, value in self.fixed_structure.items(): 87 new_dict[self.relation()][key] = serializer.serialize_field(value) 88 if isinstance(value, JSONSearchField): 89 new_dict.update(value.get_nested_options(serializer)) 90 return new_dict 91 92 def get_nested_options(self, serializer: DjangoQLSchemaSerializer) -> OrderedDict: 93 """Get keys of all nested objects to show autocomplete""" 94 if not self.suggest_nested: 95 if self.fixed_structure: 96 return self.get_fixed_structure(serializer) 97 return OrderedDict() 98 99 def recursive_function(parts: list[str], parent_parts: list[str] | None = None): 100 if not parent_parts: 101 parent_parts = [] 102 path = parts.pop(0) 103 parent_parts.append(path) 104 relation_key = "_".join(parent_parts) 105 if len(parts) > 1: 106 out_dict = { 107 relation_key: { 108 parts[0]: { 109 "type": "relation", 110 "relation": f"{relation_key}_{parts[0]}", 111 } 112 } 113 } 114 child_paths = recursive_function(parts.copy(), parent_parts.copy()) 115 child_paths.update(out_dict) 116 return child_paths 117 else: 118 return {relation_key: {parts[0]: {}}} 119 120 relation_structure = defaultdict(dict) 121 122 for relations in self.json_field_keys(): 123 result = recursive_function([self.relation()] + relations) 124 for relation_key, value in result.items(): 125 for sub_relation_key, sub_value in value.items(): 126 if not relation_structure[relation_key].get(sub_relation_key, None): 127 relation_structure[relation_key][sub_relation_key] = sub_value 128 else: 129 relation_structure[relation_key][sub_relation_key].update(sub_value) 130 131 final_dict = defaultdict(dict) 132 133 for key, value in relation_structure.items(): 134 for sub_key, sub_value in value.items(): 135 if not sub_value: 136 final_dict[key][sub_key] = { 137 "type": "str", 138 "nullable": True, 139 } 140 else: 141 final_dict[key][sub_key] = sub_value 142 return OrderedDict(final_dict) 143 144 def relation(self) -> str: 145 return f"{self.model._meta.app_label}.{self.model._meta.model_name}_{self.name}" 146 147 148class ChoiceSearchField(StrField): 149 def __init__(self, model=None, name=None, nullable=None): 150 super().__init__(model, name, nullable, suggest_options=True) 151 152 def get_options(self, search): 153 result = [] 154 choices = self._field_choices() 155 if choices: 156 search = search.lower() 157 for c in choices: 158 choice = text_type(c[0]) 159 if search in choice.lower(): 160 result.append(choice) 161 return result 162 163 164class IndexedStrField(StrField): 165 """String field which suggests the existing values of an indexed column with few distinct 166 values. `StrField` suggests them with `SELECT DISTINCT`, which reads the whole table.""" 167 168 def __init__(self, model=None, name=None, nullable=None): 169 super().__init__(model, name, nullable, suggest_options=True) 170 171 def get_options(self, search): 172 return distinct_values_containing(self.model.objects.all(), self.name, search)
17class JSONSearchField(StrField): 18 """JSON field for DjangoQL""" 19 20 model: Model 21 22 value_types = [str, bool, int, float, Decimal] 23 value_types_description = "strings, booleans or numbers" 24 25 def get_lookup_value(self, value): 26 value = super().get_lookup_value(value) 27 if isinstance(value, list): 28 return [float(item) if isinstance(item, Decimal) else item for item in value] 29 if isinstance(value, Decimal): 30 return float(value) 31 return value 32 33 def __init__( 34 self, 35 model=None, 36 name=None, 37 nullable=None, 38 suggest_nested=False, 39 fixed_structure: OrderedDict | None = None, 40 ): 41 # Set this in the constructor to not clobber the type variable 42 self.type = "relation" 43 self.suggest_nested = suggest_nested 44 self.fixed_structure = fixed_structure 45 super().__init__(model, name, nullable) 46 47 def get_lookup(self, path, operator, value): 48 search = "__".join(path) 49 op, invert = self.get_operator(operator) 50 q = Q(**{f"{search}{op}": self.get_lookup_value(value)}) 51 return ~q if invert else q 52 53 def json_field_keys(self) -> Generator[tuple[str]]: 54 with connection.cursor() as cursor: 55 cursor.execute(f""" 56 WITH RECURSIVE "{self.name}_keys" AS ( 57 SELECT 58 ARRAY[jsonb_object_keys("{self.name}")] AS key_path_array, 59 "{self.name}" -> jsonb_object_keys("{self.name}") AS value 60 FROM {self.model._meta.db_table} 61 WHERE "{self.name}" IS NOT NULL 62 AND jsonb_typeof("{self.name}") = 'object' 63 64 UNION ALL 65 66 SELECT 67 ck.key_path_array || jsonb_object_keys(ck.value), 68 ck.value -> jsonb_object_keys(ck.value) AS value 69 FROM "{self.name}_keys" ck 70 WHERE jsonb_typeof(ck.value) = 'object' 71 ), 72 73 unique_paths AS ( 74 SELECT DISTINCT key_path_array 75 FROM "{self.name}_keys" 76 ) 77 78 SELECT key_path_array FROM unique_paths; 79 """) # nosec 80 return (x[0] for x in cursor.fetchall()) 81 82 def get_fixed_structure(self, serializer: DjangoQLSchemaSerializer) -> OrderedDict: 83 new_dict = OrderedDict() 84 if not self.fixed_structure: 85 return new_dict 86 new_dict.setdefault(self.relation(), {}) 87 for key, value in self.fixed_structure.items(): 88 new_dict[self.relation()][key] = serializer.serialize_field(value) 89 if isinstance(value, JSONSearchField): 90 new_dict.update(value.get_nested_options(serializer)) 91 return new_dict 92 93 def get_nested_options(self, serializer: DjangoQLSchemaSerializer) -> OrderedDict: 94 """Get keys of all nested objects to show autocomplete""" 95 if not self.suggest_nested: 96 if self.fixed_structure: 97 return self.get_fixed_structure(serializer) 98 return OrderedDict() 99 100 def recursive_function(parts: list[str], parent_parts: list[str] | None = None): 101 if not parent_parts: 102 parent_parts = [] 103 path = parts.pop(0) 104 parent_parts.append(path) 105 relation_key = "_".join(parent_parts) 106 if len(parts) > 1: 107 out_dict = { 108 relation_key: { 109 parts[0]: { 110 "type": "relation", 111 "relation": f"{relation_key}_{parts[0]}", 112 } 113 } 114 } 115 child_paths = recursive_function(parts.copy(), parent_parts.copy()) 116 child_paths.update(out_dict) 117 return child_paths 118 else: 119 return {relation_key: {parts[0]: {}}} 120 121 relation_structure = defaultdict(dict) 122 123 for relations in self.json_field_keys(): 124 result = recursive_function([self.relation()] + relations) 125 for relation_key, value in result.items(): 126 for sub_relation_key, sub_value in value.items(): 127 if not relation_structure[relation_key].get(sub_relation_key, None): 128 relation_structure[relation_key][sub_relation_key] = sub_value 129 else: 130 relation_structure[relation_key][sub_relation_key].update(sub_value) 131 132 final_dict = defaultdict(dict) 133 134 for key, value in relation_structure.items(): 135 for sub_key, sub_value in value.items(): 136 if not sub_value: 137 final_dict[key][sub_key] = { 138 "type": "str", 139 "nullable": True, 140 } 141 else: 142 final_dict[key][sub_key] = sub_value 143 return OrderedDict(final_dict) 144 145 def relation(self) -> str: 146 return f"{self.model._meta.app_label}.{self.model._meta.model_name}_{self.name}"
JSON field for DjangoQL
33 def __init__( 34 self, 35 model=None, 36 name=None, 37 nullable=None, 38 suggest_nested=False, 39 fixed_structure: OrderedDict | None = None, 40 ): 41 # Set this in the constructor to not clobber the type variable 42 self.type = "relation" 43 self.suggest_nested = suggest_nested 44 self.fixed_structure = fixed_structure 45 super().__init__(model, name, nullable)
25 def get_lookup_value(self, value): 26 value = super().get_lookup_value(value) 27 if isinstance(value, list): 28 return [float(item) if isinstance(item, Decimal) else item for item in value] 29 if isinstance(value, Decimal): 30 return float(value) 31 return value
Override this method to convert displayed values to lookup values
47 def get_lookup(self, path, operator, value): 48 search = "__".join(path) 49 op, invert = self.get_operator(operator) 50 q = Q(**{f"{search}{op}": self.get_lookup_value(value)}) 51 return ~q if invert else q
Performs a lookup for this field with given path, operator and value.
Override this if you'd like to implement a fully custom lookup. It should support all comparison operators compatible with the field type.
:param path: a list of names preceding current lookup. For example, if expression looks like 'author.groups.name = "Foo"' path would be ['author', 'groups']. 'name' is not included, because it's the current field instance itself. :param operator: a string with comparison operator. It could be one of the following: '=', '!=', '>', '>=', '<', '<=', '~', '!~', 'in', 'not in'. Depending on the field type, some operators may be excluded. '~' and '!~' can be applied to StrField only and aren't allowed for any other fields. BoolField can't be used with less or greater operators, '>', '>=', '<' and '<=' are excluded for it. :param value: value passed for comparison :return: Q-object
53 def json_field_keys(self) -> Generator[tuple[str]]: 54 with connection.cursor() as cursor: 55 cursor.execute(f""" 56 WITH RECURSIVE "{self.name}_keys" AS ( 57 SELECT 58 ARRAY[jsonb_object_keys("{self.name}")] AS key_path_array, 59 "{self.name}" -> jsonb_object_keys("{self.name}") AS value 60 FROM {self.model._meta.db_table} 61 WHERE "{self.name}" IS NOT NULL 62 AND jsonb_typeof("{self.name}") = 'object' 63 64 UNION ALL 65 66 SELECT 67 ck.key_path_array || jsonb_object_keys(ck.value), 68 ck.value -> jsonb_object_keys(ck.value) AS value 69 FROM "{self.name}_keys" ck 70 WHERE jsonb_typeof(ck.value) = 'object' 71 ), 72 73 unique_paths AS ( 74 SELECT DISTINCT key_path_array 75 FROM "{self.name}_keys" 76 ) 77 78 SELECT key_path_array FROM unique_paths; 79 """) # nosec 80 return (x[0] for x in cursor.fetchall())
82 def get_fixed_structure(self, serializer: DjangoQLSchemaSerializer) -> OrderedDict: 83 new_dict = OrderedDict() 84 if not self.fixed_structure: 85 return new_dict 86 new_dict.setdefault(self.relation(), {}) 87 for key, value in self.fixed_structure.items(): 88 new_dict[self.relation()][key] = serializer.serialize_field(value) 89 if isinstance(value, JSONSearchField): 90 new_dict.update(value.get_nested_options(serializer)) 91 return new_dict
93 def get_nested_options(self, serializer: DjangoQLSchemaSerializer) -> OrderedDict: 94 """Get keys of all nested objects to show autocomplete""" 95 if not self.suggest_nested: 96 if self.fixed_structure: 97 return self.get_fixed_structure(serializer) 98 return OrderedDict() 99 100 def recursive_function(parts: list[str], parent_parts: list[str] | None = None): 101 if not parent_parts: 102 parent_parts = [] 103 path = parts.pop(0) 104 parent_parts.append(path) 105 relation_key = "_".join(parent_parts) 106 if len(parts) > 1: 107 out_dict = { 108 relation_key: { 109 parts[0]: { 110 "type": "relation", 111 "relation": f"{relation_key}_{parts[0]}", 112 } 113 } 114 } 115 child_paths = recursive_function(parts.copy(), parent_parts.copy()) 116 child_paths.update(out_dict) 117 return child_paths 118 else: 119 return {relation_key: {parts[0]: {}}} 120 121 relation_structure = defaultdict(dict) 122 123 for relations in self.json_field_keys(): 124 result = recursive_function([self.relation()] + relations) 125 for relation_key, value in result.items(): 126 for sub_relation_key, sub_value in value.items(): 127 if not relation_structure[relation_key].get(sub_relation_key, None): 128 relation_structure[relation_key][sub_relation_key] = sub_value 129 else: 130 relation_structure[relation_key][sub_relation_key].update(sub_value) 131 132 final_dict = defaultdict(dict) 133 134 for key, value in relation_structure.items(): 135 for sub_key, sub_value in value.items(): 136 if not sub_value: 137 final_dict[key][sub_key] = { 138 "type": "str", 139 "nullable": True, 140 } 141 else: 142 final_dict[key][sub_key] = sub_value 143 return OrderedDict(final_dict)
Get keys of all nested objects to show autocomplete
149class ChoiceSearchField(StrField): 150 def __init__(self, model=None, name=None, nullable=None): 151 super().__init__(model, name, nullable, suggest_options=True) 152 153 def get_options(self, search): 154 result = [] 155 choices = self._field_choices() 156 if choices: 157 search = search.lower() 158 for c in choices: 159 choice = text_type(c[0]) 160 if search in choice.lower(): 161 result.append(choice) 162 return result
Abstract searchable field
153 def get_options(self, search): 154 result = [] 155 choices = self._field_choices() 156 if choices: 157 search = search.lower() 158 for c in choices: 159 choice = text_type(c[0]) 160 if search in choice.lower(): 161 result.append(choice) 162 return result
Override this method to provide custom suggestion options
165class IndexedStrField(StrField): 166 """String field which suggests the existing values of an indexed column with few distinct 167 values. `StrField` suggests them with `SELECT DISTINCT`, which reads the whole table.""" 168 169 def __init__(self, model=None, name=None, nullable=None): 170 super().__init__(model, name, nullable, suggest_options=True) 171 172 def get_options(self, search): 173 return distinct_values_containing(self.model.objects.all(), self.name, search)
String field which suggests the existing values of an indexed column with few distinct
values. StrField suggests them with SELECT DISTINCT, which reads the whole table.