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.

155 lines
5.5 KiB

10 years ago
10 years ago
  1. # -*- coding: utf-8 -*-
  2. # © 2012 Therp BV (<http://therp.nl>)
  3. # License AGPL-3.0 or later (http://www.gnu.org/licenses/gpl.html).
  4. import re
  5. from odoo import models, fields, api, _, SUPERUSER_ID
  6. from odoo.exceptions import UserError
  7. import logging
  8. _logger = logging.getLogger(__name__)
  9. try:
  10. import ldap
  11. from ldap.filter import filter_format
  12. except ImportError:
  13. _logger.debug('Cannot import ldap.')
  14. class CompanyLDAP(models.Model):
  15. _inherit = 'res.company.ldap'
  16. no_deactivate_user_ids = fields.Many2many(
  17. comodel_name='res.users',
  18. relation='res_company_ldap_no_deactivate_user_rel',
  19. column1='ldap_id',
  20. column2='user_id',
  21. string='Users never to deactivate',
  22. help='List users who never should be deactivated by'
  23. ' the deactivation wizard',
  24. default=lambda self: [(6, 0, [SUPERUSER_ID])],
  25. )
  26. deactivate_unknown_users = fields.Boolean(
  27. string='Deactivate unknown users',
  28. default=False,
  29. )
  30. @api.multi
  31. def action_populate(self):
  32. """
  33. Prepopulate the user table from one or more LDAP resources.
  34. Obviously, the option to create users must be toggled in
  35. the LDAP configuration.
  36. Return the number of users created (as far as we can tell).
  37. """
  38. logger = logging.getLogger('orm.ldap')
  39. logger.debug(
  40. "action_populate called on res.company.ldap ids %s", self.ids)
  41. users_model = self.env['res.users']
  42. users_count_before = users_model.search_count([])
  43. deactivate_unknown, known_user_ids = self._check_users()
  44. if deactivate_unknown:
  45. logger.debug("will deactivate unknown users")
  46. for conf in self.get_ldap_dicts():
  47. if not conf['create_user']:
  48. continue
  49. attribute_match = re.search(
  50. r'([a-zA-Z_]+)=\%s', conf['ldap_filter'])
  51. if attribute_match:
  52. login_attr = attribute_match.group(1)
  53. else:
  54. raise UserError(
  55. _("No login attribute found: "
  56. "Could not extract login attribute from filter %s") %
  57. conf['ldap_filter'])
  58. results = self.get_ldap_entry_dicts(conf)
  59. for result in results:
  60. user_id = self.get_or_create_user(
  61. conf, result[1][login_attr][0], result)
  62. # this happens if something goes wrong while creating the user
  63. # or fetching information from ldap
  64. if not user_id:
  65. deactivate_unknown = False
  66. known_user_ids.append(user_id)
  67. users_created = users_model.search_count([]) - users_count_before
  68. deactivated_users_count = 0
  69. if deactivate_unknown:
  70. deactivated_users_count = \
  71. self.do_deactivate_unknown_users(known_user_ids)
  72. logger.debug("%d users created", users_created)
  73. logger.debug("%d users deactivated", deactivated_users_count)
  74. return users_created, deactivated_users_count
  75. def _check_users(self):
  76. deactivate_unknown = None
  77. known_user_ids = [self.env.user.id]
  78. for item in self.read(['no_deactivate_user_ids',
  79. 'deactivate_unknown_users'],
  80. load='_classic_write'):
  81. if deactivate_unknown is None:
  82. deactivate_unknown = True
  83. known_user_ids.extend(item['no_deactivate_user_ids'])
  84. deactivate_unknown &= item['deactivate_unknown_users']
  85. return deactivate_unknown, known_user_ids
  86. def get_ldap_entry_dicts(self, conf, user_name='*'):
  87. """Execute ldap query as defined in conf.
  88. Don't call self.query because it supresses possible exceptions
  89. """
  90. ldap_filter = filter_format(conf['ldap_filter'] % user_name, ())
  91. conn = self.connect(conf)
  92. conn.simple_bind_s(conf['ldap_binddn'] or '',
  93. conf['ldap_password'] or '')
  94. results = conn.search_st(conf['ldap_base'], ldap.SCOPE_SUBTREE,
  95. ldap_filter.encode('utf8'), None,
  96. timeout=60)
  97. conn.unbind()
  98. return results
  99. def do_deactivate_unknown_users(self, known_user_ids):
  100. """Deactivate users not found in last populate run."""
  101. unknown_user_ids = []
  102. users = self.env['res.users'].search(
  103. [('id', 'not in', known_user_ids)])
  104. for unknown_user in users:
  105. present_in_ldap = False
  106. for conf in self.get_ldap_dicts():
  107. present_in_ldap |= bool(self.get_ldap_entry_dicts(
  108. conf, user_name=unknown_user.login))
  109. if not present_in_ldap:
  110. unknown_user.active = False
  111. unknown_user_ids.append(unknown_user.id)
  112. return len(unknown_user_ids)
  113. @api.multi
  114. def populate_wizard(self):
  115. """
  116. GUI wrapper for the populate method that reports back
  117. the number of users created.
  118. """
  119. if not self:
  120. return
  121. wizard_obj = self.env['res.company.ldap.populate_wizard']
  122. res_id = wizard_obj.create({'ldap_id': self.id}).id
  123. return {
  124. 'name': wizard_obj._description,
  125. 'view_type': 'form',
  126. 'view_mode': 'form',
  127. 'res_model': wizard_obj._name,
  128. 'domain': [],
  129. 'context': self.env.context,
  130. 'type': 'ir.actions.act_window',
  131. 'target': 'new',
  132. 'res_id': res_id,
  133. 'nodestroy': True,
  134. }