Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

attribute.py 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. """
  2. """
  3. # Created on 2014.01.06
  4. #
  5. # Author: Giovanni Cannata
  6. #
  7. # Copyright 2014 - 2018 Giovanni Cannata
  8. #
  9. # This file is part of ldap3.
  10. #
  11. # ldap3 is free software: you can redistribute it and/or modify
  12. # it under the terms of the GNU Lesser General Public License as published
  13. # by the Free Software Foundation, either version 3 of the License, or
  14. # (at your option) any later version.
  15. #
  16. # ldap3 is distributed in the hope that it will be useful,
  17. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. # GNU Lesser General Public License for more details.
  20. #
  21. # You should have received a copy of the GNU Lesser General Public License
  22. # along with ldap3 in the COPYING and COPYING.LESSER files.
  23. # If not, see <http://www.gnu.org/licenses/>.
  24. from os import linesep
  25. from .. import MODIFY_ADD, MODIFY_REPLACE, MODIFY_DELETE, SEQUENCE_TYPES
  26. from ..core.exceptions import LDAPCursorError
  27. from ..utils.repr import to_stdout_encoding
  28. from . import STATUS_PENDING_CHANGES, STATUS_VIRTUAL, STATUS_READY_FOR_DELETION, STATUS_READY_FOR_MOVING, STATUS_READY_FOR_RENAMING
  29. from ..utils.log import log, log_enabled, ERROR, BASIC, PROTOCOL, EXTENDED
  30. # noinspection PyUnresolvedReferences
  31. class Attribute(object):
  32. """Attribute/values object, it includes the search result (after post_query transformation) of each attribute in an entry
  33. Attribute object is read only
  34. - values: contain the processed attribute values
  35. - raw_values': contain the unprocessed attribute values
  36. """
  37. def __init__(self, attr_def, entry, cursor):
  38. self.key = attr_def.key
  39. self.definition = attr_def
  40. self.values = []
  41. self.raw_values = []
  42. self.response = None
  43. self.entry = entry
  44. self.cursor = cursor
  45. other_names = [name for name in attr_def.oid_info.name if self.key.lower() != name.lower()] if attr_def.oid_info else None
  46. self.other_names = set(other_names) if other_names else None # self.other_names is None if there are no short names, else is a set of secondary names
  47. def __repr__(self):
  48. if len(self.values) == 1:
  49. r = to_stdout_encoding(self.key) + ': ' + to_stdout_encoding(self.values[0])
  50. elif len(self.values) > 1:
  51. r = to_stdout_encoding(self.key) + ': ' + to_stdout_encoding(self.values[0])
  52. filler = ' ' * (len(self.key) + 6)
  53. for value in self.values[1:]:
  54. r += linesep + filler + to_stdout_encoding(value)
  55. else:
  56. r = to_stdout_encoding(self.key) + ': ' + to_stdout_encoding('<no value>')
  57. return r
  58. def __str__(self):
  59. if len(self.values) == 1:
  60. return to_stdout_encoding(self.values[0])
  61. else:
  62. return to_stdout_encoding(self.values)
  63. def __len__(self):
  64. return len(self.values)
  65. def __iter__(self):
  66. return self.values.__iter__()
  67. def __getitem__(self, item):
  68. return self.values[item]
  69. def __eq__(self, other):
  70. try:
  71. if self.value == other:
  72. return True
  73. except Exception:
  74. return False
  75. def __ne__(self, other):
  76. return not self == other
  77. @property
  78. def value(self):
  79. """
  80. :return: The single value or a list of values of the attribute.
  81. """
  82. if not self.values:
  83. return None
  84. return self.values[0] if len(self.values) == 1 else self.values
  85. class OperationalAttribute(Attribute):
  86. """Operational attribute/values object. Include the search result of an
  87. operational attribute in an entry
  88. OperationalAttribute object is read only
  89. - values: contains the processed attribute values
  90. - raw_values: contains the unprocessed attribute values
  91. It may not have an AttrDef
  92. """
  93. def __repr__(self):
  94. if len(self.values) == 1:
  95. r = to_stdout_encoding(self.key) + ' [OPERATIONAL]: ' + to_stdout_encoding(self.values[0])
  96. elif len(self.values) > 1:
  97. r = to_stdout_encoding(self.key) + ' [OPERATIONAL]: ' + to_stdout_encoding(self.values[0])
  98. filler = ' ' * (len(self.key) + 6)
  99. for value in sorted(self.values[1:]):
  100. r += linesep + filler + to_stdout_encoding(value)
  101. else:
  102. r = ''
  103. return r
  104. class WritableAttribute(Attribute):
  105. def __repr__(self):
  106. filler = ' ' * (len(self.key) + 6)
  107. if len(self.values) == 1:
  108. r = to_stdout_encoding(self.key) + ': ' + to_stdout_encoding(self.values[0])
  109. elif len(self.values) > 1:
  110. r = to_stdout_encoding(self.key) + ': ' + to_stdout_encoding(self.values[0])
  111. for value in self.values[1:]:
  112. r += linesep + filler + to_stdout_encoding(value)
  113. else:
  114. r = to_stdout_encoding(self.key) + to_stdout_encoding(': <Virtual>')
  115. if self.definition.name in self.entry._changes:
  116. r += linesep + filler + 'CHANGES: ' + str(self.entry._changes[self.definition.name])
  117. return r
  118. def __iadd__(self, other):
  119. self.add(other)
  120. return Ellipsis # hack to avoid calling set() in entry __setattr__
  121. def __isub__(self, other):
  122. self.delete(other)
  123. return Ellipsis # hack to avoid calling set_value in entry __setattr__
  124. def _update_changes(self, changes, remove_old=False):
  125. # checks for friendly key in AttrDef and uses the real attribute name
  126. if self.definition and self.definition.name:
  127. key = self.definition.name
  128. else:
  129. key = self.key
  130. if key not in self.entry._changes or remove_old: # remove old changes (for removing attribute)
  131. self.entry._changes[key] = []
  132. self.entry._changes[key].append(changes)
  133. if log_enabled(PROTOCOL):
  134. log(PROTOCOL, 'updated changes <%r> for <%s> attribute in <%s> entry', changes, self.key, self.entry.entry_dn)
  135. self.entry._state.set_status(STATUS_PENDING_CHANGES)
  136. def add(self, values):
  137. if log_enabled(PROTOCOL):
  138. log(PROTOCOL, 'adding %r to <%s> attribute in <%s> entry', values, self.key, self.entry.entry_dn)
  139. # new value for attribute to commit with a MODIFY_ADD
  140. if self.entry._state._initial_status == STATUS_VIRTUAL:
  141. error_message = 'cannot add an attribute value in a new entry'
  142. if log_enabled(ERROR):
  143. log(ERROR, '%s for <%s>', error_message, self)
  144. raise LDAPCursorError(error_message)
  145. if self.entry.entry_status in [STATUS_READY_FOR_DELETION, STATUS_READY_FOR_MOVING, STATUS_READY_FOR_RENAMING]:
  146. error_message = self.entry.entry_status + ' - cannot add attributes'
  147. if log_enabled(ERROR):
  148. log(ERROR, '%s for <%s>', error_message, self)
  149. raise LDAPCursorError(error_message)
  150. if values is None:
  151. error_message = 'value to add cannot be None'
  152. if log_enabled(ERROR):
  153. log(ERROR, '%s for <%s>', error_message, self)
  154. raise LDAPCursorError(error_message)
  155. if values is not None:
  156. validated = self.definition.validate(values) # returns True, False or a value to substitute to the actual values
  157. if validated is False:
  158. error_message = 'value \'%s\' non valid for attribute \'%s\'' % (values, self.key)
  159. if log_enabled(ERROR):
  160. log(ERROR, '%s for <%s>', error_message, self)
  161. raise LDAPCursorError(error_message)
  162. elif validated is not True: # a valid LDAP value equivalent to the actual values
  163. values = validated
  164. self._update_changes((MODIFY_ADD, values if isinstance(values, SEQUENCE_TYPES) else [values]))
  165. def set(self, values):
  166. # new value for attribute to commit with a MODIFY_REPLACE, old values are deleted
  167. if log_enabled(PROTOCOL):
  168. log(PROTOCOL, 'setting %r to <%s> attribute in <%s> entry', values, self.key, self.entry.entry_dn)
  169. if self.entry.entry_status in [STATUS_READY_FOR_DELETION, STATUS_READY_FOR_MOVING, STATUS_READY_FOR_RENAMING]:
  170. error_message = self.entry.entry_status + ' - cannot set attributes'
  171. if log_enabled(ERROR):
  172. log(ERROR, '%s for <%s>', error_message, self)
  173. raise LDAPCursorError(error_message)
  174. if values is None:
  175. error_message = 'new value cannot be None'
  176. if log_enabled(ERROR):
  177. log(ERROR, '%s for <%s>', error_message, self)
  178. raise LDAPCursorError(error_message)
  179. validated = self.definition.validate(values) # returns True, False or a value to substitute to the actual values
  180. if validated is False:
  181. error_message = 'value \'%s\' non valid for attribute \'%s\'' % (values, self.key)
  182. if log_enabled(ERROR):
  183. log(ERROR, '%s for <%s>', error_message, self)
  184. raise LDAPCursorError(error_message)
  185. elif validated is not True: # a valid LDAP value equivalent to the actual values
  186. values = validated
  187. self._update_changes((MODIFY_REPLACE, values if isinstance(values, SEQUENCE_TYPES) else [values]), remove_old=True)
  188. def delete(self, values):
  189. # value for attribute to delete in commit with a MODIFY_DELETE
  190. if log_enabled(PROTOCOL):
  191. log(PROTOCOL, 'deleting %r from <%s> attribute in <%s> entry', values, self.key, self.entry.entry_dn)
  192. if self.entry._state._initial_status == STATUS_VIRTUAL:
  193. error_message = 'cannot delete an attribute value in a new entry'
  194. if log_enabled(ERROR):
  195. log(ERROR, '%s for <%s>', error_message, self)
  196. raise LDAPCursorError(error_message)
  197. if self.entry.entry_status in [STATUS_READY_FOR_DELETION, STATUS_READY_FOR_MOVING, STATUS_READY_FOR_RENAMING]:
  198. error_message = self.entry.entry_status + ' - cannot delete attributes'
  199. if log_enabled(ERROR):
  200. log(ERROR, '%s for <%s>', error_message, self)
  201. raise LDAPCursorError(error_message)
  202. if values is None:
  203. error_message = 'value to delete cannot be None'
  204. if log_enabled(ERROR):
  205. log(ERROR, '%s for <%s>', error_message, self)
  206. raise LDAPCursorError(error_message)
  207. if not isinstance(values, SEQUENCE_TYPES):
  208. values = [values]
  209. for single_value in values:
  210. if single_value not in self.values:
  211. error_message = 'value \'%s\' not present in \'%s\'' % (single_value, ', '.join(self.values))
  212. if log_enabled(ERROR):
  213. log(ERROR, '%s for <%s>', error_message, self)
  214. raise LDAPCursorError(error_message)
  215. self._update_changes((MODIFY_DELETE, values))
  216. def remove(self):
  217. if log_enabled(PROTOCOL):
  218. log(PROTOCOL, 'removing <%s> attribute in <%s> entry', self.key, self.entry.entry_dn)
  219. if self.entry._state._initial_status == STATUS_VIRTUAL:
  220. error_message = 'cannot remove an attribute in a new entry'
  221. if log_enabled(ERROR):
  222. log(ERROR, '%s for <%s>', error_message, self)
  223. raise LDAPCursorError(error_message)
  224. if self.entry.entry_status in [STATUS_READY_FOR_DELETION, STATUS_READY_FOR_MOVING, STATUS_READY_FOR_RENAMING]:
  225. error_message = self.entry.entry_status + ' - cannot remove attributes'
  226. if log_enabled(ERROR):
  227. log(ERROR, '%s for <%s>', error_message, self)
  228. raise LDAPCursorError(error_message)
  229. self._update_changes((MODIFY_REPLACE, []), True)
  230. def discard(self):
  231. if log_enabled(PROTOCOL):
  232. log(PROTOCOL, 'discarding <%s> attribute in <%s> entry', self.key, self.entry.entry_dn)
  233. del self.entry._changes[self.key]
  234. if not self.entry._changes:
  235. self.entry._state.set_status(self.entry._state._initial_status)
  236. @property
  237. def virtual(self):
  238. return False if len(self.values) else True
  239. @property
  240. def changes(self):
  241. if self.key in self.entry._changes:
  242. return self.entry._changes[self.key]
  243. return None