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.

81 lines
2.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, api, _
  6. from odoo.exceptions import UserError
  7. import logging
  8. _logger = logging.getLogger(__name__)
  9. try:
  10. from ldap.filter import filter_format
  11. except ImportError:
  12. _logger.debug('Can not `from ldap.filter import filter_format`.')
  13. class CompanyLDAP(models.Model):
  14. _inherit = 'res.company.ldap'
  15. @api.multi
  16. def action_populate(self):
  17. """
  18. Prepopulate the user table from one or more LDAP resources.
  19. Obviously, the option to create users must be toggled in
  20. the LDAP configuration.
  21. Return the number of users created (as far as we can tell).
  22. """
  23. users_pool = self.env['res.users']
  24. users_no_before = users_pool.search_count([])
  25. logger = logging.getLogger('orm.ldap')
  26. logger.debug("action_populate called on res.company.ldap ids %s",
  27. self.ids)
  28. for conf in self.get_ldap_dicts():
  29. if not conf['create_user']:
  30. continue
  31. attribute_match = re.search(
  32. r'([a-zA-Z_]+)=\%s', conf['ldap_filter'])
  33. if attribute_match:
  34. login_attr = attribute_match.group(1)
  35. else:
  36. raise UserError(
  37. _("No login attribute found: "
  38. "Could not extract login attribute from filter %s") %
  39. conf['ldap_filter'])
  40. ldap_filter = filter_format(conf['ldap_filter'] % '*', ())
  41. for result in self.query(conf, ldap_filter.encode('utf-8')):
  42. self.get_or_create_user(conf, result[1][login_attr][0], result)
  43. users_no_after = users_pool.search_count([])
  44. users_created = users_no_after - users_no_before
  45. logger.debug("%d users created", users_created)
  46. return users_created
  47. @api.multi
  48. def populate_wizard(self):
  49. """
  50. GUI wrapper for the populate method that reports back
  51. the number of users created.
  52. """
  53. if not self:
  54. return
  55. wizard_obj = self.env['res.company.ldap.populate_wizard']
  56. res_id = wizard_obj.create({'ldap_id': self.id}).id
  57. return {
  58. 'name': wizard_obj._description,
  59. 'view_type': 'form',
  60. 'view_mode': 'form',
  61. 'res_model': wizard_obj._name,
  62. 'domain': [],
  63. 'context': self.env.context,
  64. 'type': 'ir.actions.act_window',
  65. 'target': 'new',
  66. 'res_id': res_id,
  67. 'nodestroy': True,
  68. }