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.

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