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.
 
 
 
 

100 lines
2.9 KiB

  1. # -*- coding: utf-8 -*-
  2. from flask import current_app
  3. from ldap3 import AttrDef
  4. from ldap3.core.exceptions import LDAPAttributeError
  5. from ldap3 import (STRING_TYPES, NUMERIC_TYPES, MODIFY_ADD, MODIFY_DELETE,
  6. MODIFY_REPLACE)
  7. class LdapField(object):
  8. def __init__(self, name, validate=None, default=None, dereference_dn=None):
  9. self.name = name
  10. self.validate = validate
  11. self.default = default
  12. self.dereference_dn = None
  13. def get_abstract_attr_def(self, key):
  14. return AttrDef(name=self.name, key=key,
  15. validate=self.validate,
  16. default=self.default,
  17. dereference_dn=self.dereference_dn)
  18. class LDAPAttribute(object):
  19. def __init__(self, name):
  20. self.__dict__['name'] = name
  21. self.__dict__['values'] = []
  22. self.__dict__['changetype'] = None
  23. def __str__(self):
  24. if isinstance(self.value, STRING_TYPES):
  25. return self.value
  26. else:
  27. return str(self.value)
  28. def __len__(self):
  29. return len(self.values)
  30. def __iter__(self):
  31. return self.values.__iter__()
  32. def __contains__(self, item):
  33. return item in self.__dict__['values']
  34. def __setattr__(self, item, value):
  35. if item not in ['value', '_init']:
  36. raise LDAPAttributeError('can not set key')
  37. # set changetype
  38. if item == 'value':
  39. if self.__dict__['values']:
  40. if not value:
  41. self.__dict__['changetype'] = MODIFY_DELETE
  42. else:
  43. self.__dict__['changetype'] = MODIFY_REPLACE
  44. else:
  45. self.__dict__['changetype'] = MODIFY_ADD
  46. if isinstance(value, (STRING_TYPES, NUMERIC_TYPES)):
  47. value = [value]
  48. self.__dict__['values'] = value
  49. @property
  50. def value(self):
  51. '''Return single value or list of values from the attribute.
  52. If FORCE_ATTRIBUTE_VALUE_AS_LIST is True, always return a
  53. list with values.
  54. '''
  55. if len(self.__dict__['values']) == 1 and current_app.config['FORCE_ATTRIBUTE_VALUE_AS_LIST'] is False:
  56. return self.__dict__['values'][0]
  57. else:
  58. return self.__dict__['values']
  59. @property
  60. def changetype(self):
  61. return self.__dict__['changetype']
  62. def get_changes_tuple(self):
  63. values = [val.encode('UTF-8') for val in self.__dict__['values']]
  64. return (self.changetype, values)
  65. def append(self, value):
  66. '''Add another value to the attribute'''
  67. if self.__dict__['values']:
  68. self.__dict__['changetype'] = MODIFY_REPLACE
  69. self.__dict__['values'].append(value)
  70. def delete(self):
  71. '''Delete this attribute
  72. This property sets the value to an empty list an the changetype
  73. to delete.
  74. '''
  75. self.value = []