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.

187 lines
6.8 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. ldap_password = conf['ldap_password'] or ''
  112. ldap_binddn = conf['ldap_binddn'] or ''
  113. conn.simple_bind_s(
  114. ldap_binddn.encode('utf-8'),
  115. ldap_password.encode('utf-8')
  116. )
  117. results = conn.search_st(
  118. conf['ldap_base'].encode('utf-8'),
  119. ldap.SCOPE_SUBTREE,
  120. ldap_filter.encode('utf8'),
  121. None,
  122. timeout=timeout
  123. )
  124. conn.unbind()
  125. return results
  126. def do_deactivate_unknown_users(self, known_user_ids):
  127. """Deactivate users not found in last populate run."""
  128. unknown_user_ids = []
  129. known_user_ids = list(set(known_user_ids))
  130. users = self.env['res.users'].sudo().search(
  131. [('id', 'not in', known_user_ids)], order='login')
  132. ldap_confs = self.get_ldap_dicts()
  133. for unknown_user in users:
  134. _logger.debug('checking user %s', unknown_user.login)
  135. present_in_ldap = any(
  136. bool(
  137. self.get_ldap_entry_dicts(
  138. conf,
  139. user_name=unknown_user.login,
  140. ))
  141. for conf in ldap_confs
  142. )
  143. if not present_in_ldap:
  144. _logger.debug('archiving user %s', unknown_user.login)
  145. unknown_user.active = False
  146. unknown_user_ids.append(unknown_user.id)
  147. return len(unknown_user_ids)
  148. @api.multi
  149. def populate_wizard(self):
  150. """
  151. GUI wrapper for the populate method that reports back
  152. the number of users created.
  153. """
  154. if not self:
  155. return
  156. wizard_obj = self.env['res.company.ldap.populate_wizard']
  157. res_id = wizard_obj.create({'ldap_id': self.id}).id
  158. return {
  159. 'name': wizard_obj._description,
  160. 'view_type': 'form',
  161. 'view_mode': 'form',
  162. 'res_model': wizard_obj._name,
  163. 'domain': [],
  164. 'context': self.env.context,
  165. 'type': 'ir.actions.act_window',
  166. 'target': 'new',
  167. 'res_id': res_id,
  168. 'nodestroy': True,
  169. }