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.

156 lines
5.6 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.with_context(
  61. no_reset_password=True
  62. ).get_or_create_user(conf, result[1][login_attr][0], result)
  63. # this happens if something goes wrong while creating the user
  64. # or fetching information from ldap
  65. if not user_id:
  66. deactivate_unknown = False
  67. known_user_ids.append(user_id)
  68. users_created = users_model.search_count([]) - users_count_before
  69. deactivated_users_count = 0
  70. if deactivate_unknown:
  71. deactivated_users_count = \
  72. self.do_deactivate_unknown_users(known_user_ids)
  73. logger.debug("%d users created", users_created)
  74. logger.debug("%d users deactivated", deactivated_users_count)
  75. return users_created, deactivated_users_count
  76. def _check_users(self):
  77. deactivate_unknown = None
  78. known_user_ids = [self.env.user.id]
  79. for item in self.read(['no_deactivate_user_ids',
  80. 'deactivate_unknown_users'],
  81. load='_classic_write'):
  82. if deactivate_unknown is None:
  83. deactivate_unknown = True
  84. known_user_ids.extend(item['no_deactivate_user_ids'])
  85. deactivate_unknown &= item['deactivate_unknown_users']
  86. return deactivate_unknown, known_user_ids
  87. def get_ldap_entry_dicts(self, conf, user_name='*'):
  88. """Execute ldap query as defined in conf.
  89. Don't call self.query because it supresses possible exceptions
  90. """
  91. ldap_filter = filter_format(conf['ldap_filter'] % user_name, ())
  92. conn = self.connect(conf)
  93. conn.simple_bind_s(conf['ldap_binddn'] or '',
  94. conf['ldap_password'] or '')
  95. results = conn.search_st(conf['ldap_base'], ldap.SCOPE_SUBTREE,
  96. ldap_filter.encode('utf8'), None,
  97. timeout=60)
  98. conn.unbind()
  99. return results
  100. def do_deactivate_unknown_users(self, known_user_ids):
  101. """Deactivate users not found in last populate run."""
  102. unknown_user_ids = []
  103. users = self.env['res.users'].search(
  104. [('id', 'not in', known_user_ids)])
  105. for unknown_user in users:
  106. present_in_ldap = False
  107. for conf in self.get_ldap_dicts():
  108. present_in_ldap |= bool(self.get_ldap_entry_dicts(
  109. conf, user_name=unknown_user.login))
  110. if not present_in_ldap:
  111. unknown_user.active = False
  112. unknown_user_ids.append(unknown_user.id)
  113. return len(unknown_user_ids)
  114. @api.multi
  115. def populate_wizard(self):
  116. """
  117. GUI wrapper for the populate method that reports back
  118. the number of users created.
  119. """
  120. if not self:
  121. return
  122. wizard_obj = self.env['res.company.ldap.populate_wizard']
  123. res_id = wizard_obj.create({'ldap_id': self.id}).id
  124. return {
  125. 'name': wizard_obj._description,
  126. 'view_type': 'form',
  127. 'view_mode': 'form',
  128. 'res_model': wizard_obj._name,
  129. 'domain': [],
  130. 'context': self.env.context,
  131. 'type': 'ir.actions.act_window',
  132. 'target': 'new',
  133. 'res_id': res_id,
  134. 'nodestroy': True,
  135. }