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.

179 lines
6.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('orm.ldap')
  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.debug(
  39. "action_populate called on res.company.ldap ids %s", self.ids)
  40. users_model = self.env['res.users']
  41. users_count_before = users_model.search_count([])
  42. deactivate_unknown, known_user_ids = self._check_users()
  43. if deactivate_unknown:
  44. _logger.debug("will deactivate unknown users")
  45. for conf in self.get_ldap_dicts():
  46. if not conf['create_user']:
  47. continue
  48. attribute_match = re.search(
  49. r'([a-zA-Z_]+)=\%s', conf['ldap_filter'])
  50. if attribute_match:
  51. login_attr = attribute_match.group(1)
  52. else:
  53. raise UserError(
  54. _("No login attribute found: "
  55. "Could not extract login attribute from filter %s") %
  56. conf['ldap_filter'])
  57. results = self.get_ldap_entry_dicts(conf)
  58. for result in results:
  59. login = result[1][login_attr][0].lower().strip()
  60. user_id = self.with_context(
  61. no_reset_password=True
  62. ).get_or_create_user(conf, login, result)
  63. if not user_id:
  64. # this happens if the user exists but is active = False
  65. # -> fetch the user again and reactivate it
  66. self.env.cr.execute(
  67. "SELECT id FROM res_users "
  68. "WHERE lower(login)=%s",
  69. (login,))
  70. res = self.env.cr.fetchone()
  71. _logger.debug('unarchiving user %s', login)
  72. if res:
  73. self.env['res.users'].sudo().browse(
  74. res[0]
  75. ).write(
  76. {'active': True}
  77. )
  78. user_id = res[0]
  79. else:
  80. raise UserError(
  81. 'Unable to process user with login %s' % login
  82. )
  83. known_user_ids.append(user_id)
  84. users_created = users_model.search_count([]) - users_count_before
  85. deactivated_users_count = 0
  86. if deactivate_unknown:
  87. deactivated_users_count = \
  88. self.do_deactivate_unknown_users(known_user_ids)
  89. _logger.debug("%d users created", users_created)
  90. _logger.debug("%d users deactivated", deactivated_users_count)
  91. return users_created, deactivated_users_count
  92. def _check_users(self):
  93. ldap_config = self.search([])
  94. deactivate_unknown = None
  95. known_user_ids = [self.env.user.id]
  96. for item in ldap_config.read(
  97. ['no_deactivate_user_ids',
  98. 'deactivate_unknown_users'],
  99. load='_classic_write'):
  100. if deactivate_unknown is None:
  101. deactivate_unknown = True
  102. known_user_ids.extend(item['no_deactivate_user_ids'])
  103. deactivate_unknown &= item['deactivate_unknown_users']
  104. return deactivate_unknown, known_user_ids
  105. def get_ldap_entry_dicts(self, conf, user_name='*', timeout=60):
  106. """Execute ldap query as defined in conf.
  107. Don't call self.query because it supresses possible exceptions
  108. """
  109. ldap_filter = filter_format(conf['ldap_filter'] % user_name, ())
  110. conn = self.connect(conf)
  111. conn.simple_bind_s(conf['ldap_binddn'] or '',
  112. conf['ldap_password'] or '')
  113. results = conn.search_st(conf['ldap_base'], ldap.SCOPE_SUBTREE,
  114. ldap_filter.encode('utf8'), None,
  115. timeout=timeout)
  116. conn.unbind()
  117. return results
  118. def do_deactivate_unknown_users(self, known_user_ids):
  119. """Deactivate users not found in last populate run."""
  120. unknown_user_ids = []
  121. known_user_ids = list(set(known_user_ids))
  122. users = self.env['res.users'].sudo().search(
  123. [('id', 'not in', known_user_ids)], order='login')
  124. ldap_confs = self.get_ldap_dicts()
  125. for unknown_user in users:
  126. _logger.debug('checking user %s', unknown_user.login)
  127. present_in_ldap = any(
  128. bool(
  129. self.get_ldap_entry_dicts(
  130. conf,
  131. user_name=unknown_user.login,
  132. ))
  133. for conf in ldap_confs
  134. )
  135. if not present_in_ldap:
  136. _logger.debug('archiving user %s', unknown_user.login)
  137. unknown_user.active = False
  138. unknown_user_ids.append(unknown_user.id)
  139. return len(unknown_user_ids)
  140. @api.multi
  141. def populate_wizard(self):
  142. """
  143. GUI wrapper for the populate method that reports back
  144. the number of users created.
  145. """
  146. if not self:
  147. return
  148. wizard_obj = self.env['res.company.ldap.populate_wizard']
  149. res_id = wizard_obj.create({'ldap_id': self.id}).id
  150. return {
  151. 'name': wizard_obj._description,
  152. 'view_type': 'form',
  153. 'view_mode': 'form',
  154. 'res_model': wizard_obj._name,
  155. 'domain': [],
  156. 'context': self.env.context,
  157. 'type': 'ir.actions.act_window',
  158. 'target': 'new',
  159. 'res_id': res_id,
  160. 'nodestroy': True,
  161. }