Debian Codegraph @

src/bonsai/ldapentry.py

raw symbols SCIP
1 from enum import IntEnum
2 from typing import (
3 Union,
4 TypeVar,
5 Any,
6 Tuple,
7 Dict,
8 Optional,
9 KeysView,
10 ItemsView,
11 ValuesView,
12 Iterator,
13 )
14
15 from bonsai._bonsai import ldapentry
16 from .errors import InvalidDN
17 from .ldapdn import LDAPDN
18 from .ldapvaluelist import LDAPValueList
19
20 MYPY = False
21
22 if MYPY:
23 from .ldapconnection import BaseLDAPConnection
24
25 CT = TypeVar("CT", bound="BaseLDAPConnection")
26
27
28 class LDAPModOp(IntEnum):
29 """Enumeration for LDAP modification operations."""
30
31 ADD = 0 #: For adding new values to the attribute.
32 DELETE = 1 #: For deleting existing values from the attribute list.
33 REPLACE = 2 #: For replacing the existing attribute values.
34
35
36 class LDAPEntry(ldapentry):
37 def __init__(self, dn: Union[LDAPDN, str], conn: Optional[CT] = None) -> None:
38 try:
39 super().__init__(dn, conn)
40 self.__extended_dn = None # type: Optional[str]
41 except InvalidDN as exc:
42 # InvalidDN error caused by extended DN control.
43 splitted_dn = str(dn).split(";")
44 try:
45 super().__init__(splitted_dn[-1], conn)
46 except InvalidDN:
47 raise exc from None
48 self.__extended_dn = str(dn)
49
50 def delete(self, timeout: Optional[float] = None, recursive: bool = False) -> Any:
51 """
52 Remove LDAP entry from the dictionary server.
53
54 :param float timeout: time limit in seconds for the operation.
55 :param bool recursive: remove every entry of the given subtree \
56 recursively.
57 :return: True, if the operation is finished.
58 :rtype: bool
59 """
60 res = self.connection.delete(self.dn, timeout, recursive)
61 for value in self.values():
62 try:
63 value.status = 2
64 except AttributeError:
65 continue # Skip DN.
66 return res
67
68 def modify(self, timeout: Optional[float] = None) -> Any:
69 """
70 Send entry's modifications to the dictionary server.
71
72 :param float timeout: time limit in seconds for the operation.
73 :return: True, if the operation is finished.
74 :rtype: bool
75 """
76 return self.connection._evaluate(super().modify(), timeout)
77
78 def rename(
79 self,
80 newdn: Union[str, LDAPDN],
81 timeout: Optional[float] = None,
82 delete_old_rdn: bool = True,
83 ) -> Any:
84 """
85 Change the entry's distinguished name.
86
87 :param str|LDAPDN newdn: the new DN of the entry.
88 :param float timeout: time limit in seconds for the operation.
89 :param bool delete_old_rdn: remove old RDN with renaming.
90 :return: True, if the operation is finished.
91 :rtype: bool
92 """
93 if isinstance(newdn, LDAPDN):
94 newdn = str(newdn)
95 return self.connection._evaluate(super().rename(newdn, delete_old_rdn), timeout)
96
97 def update(self, *args: Tuple, **kwds: Dict[str, Any]) -> None:
98 """
99 Update the LDAPEntry with the key/value pairs from other, overwriting existing keys.
100 (Same as dict's update method.)
101 """
102 if args:
103 if hasattr(args[0], "keys"):
104 # Working with a dict on the parameter list.
105 for key, value in args[0].items():
106 self.__setitem__(key, value)
107 else:
108 # Working with a sequence.
109 for tup in args[0]:
110 if len(tup) != 2:
111 raise ValueError("Sequence element has more then 2 element.")
112 self.__setitem__(tup[0], tup[1])
113 if kwds:
114 # Key/value pairs are listed on the parameter list.
115 for key, value in kwds.items():
116 self.__setitem__(key, value)
117
118 def clear(self) -> None:
119 """Remove all items from the dictionary."""
120 keys = list(self.keys())
121 for key in keys:
122 try:
123 del self[key]
124 except TypeError:
125 continue # Skip DN.
126
127 def get(self, key: str, default: Any = None) -> Any:
128 """
129 Return the value for `key` if `key` is in the LDAPEntry,
130 else `default`. (Same as dict's get method.)
131 """
132 try:
133 return self[key]
134 except KeyError:
135 return default
136
137 def pop(self, *args: Tuple) -> Any:
138 """
139 LDAPEntry.pop(k[,d]) -> v, remove specified key and return the
140 corresponding value. If key is not found, d is returned if given,
141 otherwise KeyError is raised.
142
143 :param key: the key.
144 :param dflt: if key is not found, d is returned.
145 :return: the value from the LDAPEntry.
146 """
147 if len(args) > 2:
148 raise TypeError("pop expected at most 2 arguments, got %d" % len(args))
149 try:
150 key = args[0]
151 value = self[key]
152 del self[key]
153 return value
154 except IndexError:
155 raise TypeError("pop expected at least 1 arguments, got 0")
156 except KeyError as err:
157 try:
158 dflt = args[1]
159 return dflt
160 except IndexError:
161 raise err
162
163 def popitem(self) -> Tuple[str, Any]:
164 """
165 LDAPEntry.popitem() -> (k, v), remove and return some (key, value)
166 pair as a 2-tuple; but raise KeyError if LDAPEntry is empty.
167 """
168 try:
169 keylist = LDAPValueList(self.keys())
170 keylist.remove("dn")
171 key = keylist.pop(0)
172 value = self[key]
173 del self[key]
174 return (key, value)
175 except IndexError:
176 raise KeyError("popitem(): LDAPEntry is empty")
177
178 def __eq__(self, other: object) -> bool:
179 """
180 Two LDAPEntry objects are considered equals, if their DN is the same.
181
182 :param other: the other comparable object.
183 :return: True if the two object are equals.
184 :rtype: bool
185 """
186 if isinstance(other, self.__class__):
187 return self.dn == other.dn
188 else:
189 return super().__eq__(other)
190
191 def _status(self) -> Dict:
192 status = {}
193 for key, value in self.items():
194 try:
195 status[key] = value._status_dict
196 except AttributeError:
197 continue # Skip DN
198 status["@deleted_keys"] = self.deleted_keys
199 return status
200
201 @property
202 def extended_dn(self) -> Optional[str]:
203 """
204 The extended DN of the entry. It is None, if the extended DN control
205 is not set or not supported. The attribute is read-only.
206 """
207 return self.__extended_dn
208
209 def change_attribute(self, name: str, optype: int, *values: Tuple) -> None:
210 """
211 Change an attribute of the entry with explicit LDAP modification type
212 by listing the values as parameters.
213 An attribute can be removed entirely if the `optype` is delete and no
214 `values` are passed.
215 This method can be useful for changing write-only attributes (e.g.
216 passwords).
217
218 :param str name: the name of the attribute.
219 :param int optype: the operation type, 0 for adding, 1 for deleting \
220 and 2 for replacing. An :class:`LDAPModOp` also can be used as value.
221 :param \\*values: the new value or values of the attribute.
222 """
223 lvl = self.get(name, LDAPValueList())
224 if optype == LDAPModOp.ADD:
225 lvl.added.extend(values)
226 for val in values:
227 lvl._append_unchecked(val)
228 elif optype == LDAPModOp.DELETE:
229 if len(values) == 0:
230 self.__setitem__(name, None)
231 del self[name]
232 return
233 else:
234 lvl.deleted.extend(values)
235 for val in values:
236 lvl._remove_unchecked(val)
237 elif optype == LDAPModOp.REPLACE:
238 lvl = LDAPValueList(values)
239 else:
240 raise ValueError("Wrong operation type.")
241 self[name] = lvl
242 lvl.status = 2 if optype == 2 else 1
243
244 def clear_attribute_changes(self, name: str) -> None:
245 """
246 Clear all added and deleted changes of an attribute.
247
248 :param str name: the name of the attribute.
249 """
250 lvl = self.get(name, LDAPValueList())
251 lvl.added.clear()
252 lvl.deleted.clear()
253 self[name] = lvl
254 lvl.status = 0
255
256 def items(self, *, exclude_dn: bool = False) -> Union[ItemsView, Iterator]:
257 """
258 Same functionality as dict.items() but with an optional `exclude_dn`
259 keyword-only argument. When `exclude_dn` is True it returns a
260 generator of the LDAPEntry's key-value pairs without the dn key and value.
261
262 :param bool exclude_dn: exclude dn key from the list.
263 :return: sequence of key-value pairs.
264 :rtype: dict_items, generator
265 """
266 if exclude_dn:
267 return (item for item in super().items() if item[0] != "dn")
268 else:
269 return super().items()
270
271 def keys(self, *, exclude_dn: bool = False) -> Union[KeysView, Iterator]:
272 """
273 Same functionality as dict.keys() but with an optional `exclude_dn`
274 keyword-only argument. When `exclude_dn` is True it returns a
275 generator of the LDAPEntry's keys without the dn key.
276
277 :param bool exclude_dn: exclude dn key from the list.
278 :return: sequence of keys.
279 :rtype: dict_keys, generator
280 """
281 if exclude_dn:
282 return (key for key in super().keys() if key != "dn")
283 else:
284 return super().keys()
285
286 def values(self, *, exclude_dn: bool = False) -> Union[ValuesView, Iterator]:
287 """
288 Same functionality as dict.values() but with an optional `exclude_dn`
289 keyword-only argument. When `exclude_dn` is True it returns a
290 generator of the LDAPEntry's values without the value of the dn key.
291
292 :param bool exclude_dn: exclude dn key from the list.
293 :return: sequence of values.
294 :rtype: dict_values, generator
295 """
296 if exclude_dn:
297 return (item for item in super().values() if item is not self.dn)
298 else:
299 return super().values()