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.

192 lines
7.1 KiB

10 years ago
10 years ago
  1. # -*- coding: utf-8 -*-
  2. ##############################################################################
  3. #
  4. # OpenERP, Open Source Management Solution
  5. # This module copyright (C) 2012 Therp BV (<http://therp.nl>).
  6. #
  7. # This program is free software: you can redistribute it and/or modify
  8. # it under the terms of the GNU Affero General Public License as
  9. # published by the Free Software Foundation, either version 3 of the
  10. # License, or (at your option) any later version.
  11. #
  12. # This program is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. # GNU Affero General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU Affero General Public License
  18. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  19. #
  20. ##############################################################################
  21. import re
  22. from openerp.osv import orm, fields # pylint: disable=W0402
  23. from openerp import SUPERUSER_ID
  24. import logging
  25. _logger = logging.getLogger(__name__)
  26. try:
  27. import ldap
  28. from ldap.filter import filter_format
  29. except ImportError:
  30. _logger.debug('Cannot import ldap')
  31. class CompanyLDAP(orm.Model):
  32. _inherit = 'res.company.ldap'
  33. _columns = {
  34. 'no_deactivate_user_ids': fields.many2many(
  35. 'res.users', 'res_company_ldap_no_deactivate_user_rel',
  36. 'ldap_id', 'user_id',
  37. 'Users never to deactivate',
  38. help='List users who never should be deactivated by'
  39. ' the deactivation wizard'),
  40. 'deactivate_unknown_users': fields.boolean(
  41. 'Deactivate unknown users'),
  42. }
  43. _defaults = {
  44. 'no_deactivate_user_ids': [(6, 0, [SUPERUSER_ID])],
  45. 'deactivate_unknown_users': False,
  46. }
  47. def action_populate(self, cr, uid, ids, context=None):
  48. """
  49. Prepopulate the user table from one or more LDAP resources.
  50. Obviously, the option to create users must be toggled in
  51. the LDAP configuration.
  52. Return the number of users created (as far as we can tell).
  53. """
  54. if isinstance(ids, (int, float)):
  55. ids = [ids]
  56. users_pool = self.pool.get('res.users')
  57. users_no_before = users_pool.search(
  58. cr, uid, [], context=context, count=True)
  59. logger = logging.getLogger('orm.ldap')
  60. logger.debug("action_populate called on res.company.ldap ids %s", ids)
  61. deactivate_unknown = None
  62. known_user_ids = [uid]
  63. for this in self.read(cr, uid, ids,
  64. [
  65. 'no_deactivate_user_ids',
  66. 'deactivate_unknown_users',
  67. ],
  68. context=context, load='_classic_write'):
  69. if deactivate_unknown is None:
  70. deactivate_unknown = True
  71. known_user_ids.extend(this['no_deactivate_user_ids'])
  72. deactivate_unknown &= this['deactivate_unknown_users']
  73. if deactivate_unknown:
  74. logger.debug("will deactivate unknown users")
  75. for conf in self.get_ldap_dicts(cr, ids):
  76. if not conf['create_user']:
  77. continue
  78. attribute_match = re.search(
  79. r'([a-zA-Z_]+)=\%s', conf['ldap_filter'])
  80. if attribute_match:
  81. login_attr = attribute_match.group(1)
  82. else:
  83. raise orm.except_orm(
  84. "No login attribute found",
  85. "Could not extract login attribute from filter %s" %
  86. conf['ldap_filter'])
  87. results = self.get_ldap_entry_dicts(conf)
  88. for result in results:
  89. user_id = self.get_or_create_user(
  90. cr, uid, conf, result[1][login_attr][0], result)
  91. # this happens if something goes wrong while creating the user
  92. # or fetching information from ldap
  93. if not user_id:
  94. deactivate_unknown = False
  95. known_user_ids.append(user_id)
  96. users_no_after = users_pool.search(
  97. cr, uid, [], context=context, count=True)
  98. users_created = users_no_after - users_no_before
  99. deactivated_users_count = 0
  100. if deactivate_unknown:
  101. deactivated_users_count = self.do_deactivate_unknown_users(
  102. cr, uid, ids, known_user_ids, context=context)
  103. logger.debug("%d users created", users_created)
  104. logger.debug("%d users deactivated", deactivated_users_count)
  105. return users_created, deactivated_users_count
  106. def do_deactivate_unknown_users(
  107. self, cr, uid, ids, known_user_ids, context=None):
  108. """
  109. Deactivate users not found in last populate run
  110. """
  111. res_users = self.pool.get('res.users')
  112. unknown_user_ids = []
  113. for unknown_user in res_users.read(
  114. cr, uid,
  115. res_users.search(
  116. cr, uid,
  117. [('id', 'not in', known_user_ids)],
  118. context=context),
  119. ['login'],
  120. context=context):
  121. present_in_ldap = False
  122. for conf in self.get_ldap_dicts(cr, ids):
  123. present_in_ldap |= bool(self.get_ldap_entry_dicts(
  124. conf, user_name=unknown_user['login']))
  125. if not present_in_ldap:
  126. res_users.write(
  127. cr, uid, unknown_user['id'], {'active': False},
  128. context=context)
  129. unknown_user_ids.append(unknown_user['id'])
  130. return len(unknown_user_ids)
  131. def get_ldap_entry_dicts(self, conf, user_name='*'):
  132. """
  133. Execute ldap query as defined in conf
  134. Don't call self.query because it supresses possible exceptions
  135. """
  136. ldap_filter = filter_format(conf['ldap_filter'] % user_name, ())
  137. conn = self.connect(conf)
  138. conn.simple_bind_s(conf['ldap_binddn'] or '',
  139. conf['ldap_password'] or '')
  140. results = conn.search_st(conf['ldap_base'], ldap.SCOPE_SUBTREE,
  141. ldap_filter.encode('utf8'), None,
  142. timeout=60)
  143. conn.unbind()
  144. return results
  145. def populate_wizard(self, cr, uid, ids, context=None):
  146. """
  147. GUI wrapper for the populate method that reports back
  148. the number of users created.
  149. """
  150. if not ids:
  151. return
  152. if isinstance(ids, (int, float)):
  153. ids = [ids]
  154. wizard_obj = self.pool.get('res.company.ldap.populate_wizard')
  155. res_id = wizard_obj.create(
  156. cr, uid, {'ldap_id': ids[0]}, context=context)
  157. return {
  158. 'name': wizard_obj._description,
  159. 'view_type': 'form',
  160. 'view_mode': 'form',
  161. 'res_model': wizard_obj._name,
  162. 'domain': [],
  163. 'context': context,
  164. 'type': 'ir.actions.act_window',
  165. 'target': 'new',
  166. 'res_id': res_id,
  167. 'nodestroy': True,
  168. }