1 ##############################################################################
3 # OpenERP, Open Source Management Solution
4 # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
6 # This program is free software: you can redistribute it and/or modify
7 # it under the terms of the GNU Affero General Public License as
8 # published by the Free Software Foundation, either version 3 of the
9 # License, or (at your option) any later version.
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU Affero General Public License for more details.
16 # You should have received a copy of the GNU Affero General Public License
17 # along with this program. If not, see <http://www.gnu.org/licenses/>.
19 ##############################################################################
23 from ldap.filter import filter_format
25 import openerp.exceptions
26 from openerp import tools
27 from openerp.osv import fields, osv
28 from openerp import SUPERUSER_ID
29 from openerp.modules.registry import RegistryManager
30 _logger = logging.getLogger(__name__)
32 class CompanyLDAP(osv.osv):
33 _name = 'res.company.ldap'
35 _rec_name = 'ldap_server'
37 def get_ldap_dicts(self, cr, ids=None):
39 Retrieve res_company_ldap resources from the database in dictionary
42 :param list ids: Valid ids of model res_company_ldap. If not \
43 specified, process all resources (unlike other ORM methods).
44 :return: ldap configurations
45 :rtype: list of dictionaries
49 id_clause = 'AND id IN (%s)'
55 SELECT id, company, ldap_server, ldap_server_port, ldap_binddn,
56 ldap_password, ldap_filter, ldap_base, "user", create_user,
59 WHERE ldap_server != '' """ + id_clause + """ ORDER BY sequence
61 return cr.dictfetchall()
63 def connect(self, conf):
65 Connect to an LDAP server specified by an ldap
66 configuration dictionary.
68 :param dict conf: LDAP configuration
69 :return: an LDAP object
72 uri = 'ldap://%s:%d' % (conf['ldap_server'],
73 conf['ldap_server_port'])
75 connection = ldap.initialize(uri)
77 connection.start_tls_s()
80 def authenticate(self, conf, login, password):
82 Authenticate a user against the specified LDAP server.
84 In order to prevent an unintended 'unauthenticated authentication',
85 which is an anonymous bind with a valid dn and a blank password,
86 check for empty passwords explicitely (:rfc:`4513#section-6.3.1`)
88 :param dict conf: LDAP configuration
89 :param login: username
90 :param password: Password for the LDAP user
91 :return: LDAP entry of authenticated user or False
92 :rtype: dictionary of attributes
99 filter = filter_format(conf['ldap_filter'], (login,))
101 results = self.query(conf, filter)
102 if results and len(results) == 1:
104 conn = self.connect(conf)
105 conn.simple_bind_s(dn, password)
108 except ldap.INVALID_CREDENTIALS:
110 except ldap.LDAPError, e:
111 _logger.error('An LDAP exception occurred: %s', e)
114 def query(self, conf, filter, retrieve_attributes=None):
116 Query an LDAP server with the filter argument and scope subtree.
118 Allow for all authentication methods of the simple authentication
121 - authenticated bind (non-empty binddn + valid password)
122 - anonymous bind (empty binddn + empty password)
123 - unauthenticated authentication (non-empty binddn + empty password)
126 :rfc:`4513#section-5.1` - LDAP: Simple Authentication Method.
128 :param dict conf: LDAP configuration
129 :param filter: valid LDAP filter
130 :param list retrieve_attributes: LDAP attributes to be retrieved. \
131 If not specified, return all attributes.
132 :return: ldap entries
133 :rtype: list of tuples (dn, attrs)
139 conn = self.connect(conf)
140 conn.simple_bind_s(conf['ldap_binddn'] or '',
141 conf['ldap_password'] or '')
142 results = conn.search_st(conf['ldap_base'], ldap.SCOPE_SUBTREE,
143 filter, retrieve_attributes, timeout=60)
145 except ldap.INVALID_CREDENTIALS:
146 _logger.error('LDAP bind failed.')
147 except ldap.LDAPError, e:
148 _logger.error('An LDAP exception occurred: %s', e)
151 def map_ldap_attributes(self, cr, uid, conf, login, ldap_entry):
153 Compose values for a new resource of model res_users,
154 based upon the retrieved ldap entry and the LDAP settings.
156 :param dict conf: LDAP configuration
157 :param login: the new user's login
158 :param tuple ldap_entry: single LDAP result (dn, attrs)
159 :return: parameters for a new resource of model res_users
163 values = { 'name': ldap_entry[1]['cn'][0],
165 'company_id': conf['company']
169 def get_or_create_user(self, cr, uid, conf, login, ldap_entry,
172 Retrieve an active resource of model res_users with the specified
173 login. Create the user if it is not initially found.
175 :param dict conf: LDAP configuration
176 :param login: the user's login
177 :param tuple ldap_entry: single LDAP result (dn, attrs)
178 :return: res_users id
183 login = tools.ustr(login.lower())
184 cr.execute("SELECT id, active FROM res_users WHERE lower(login)=%s", (login,))
189 elif conf['create_user']:
190 _logger.debug("Creating new OpenERP user \"%s\" from LDAP" % login)
191 user_obj = self.pool['res.users']
192 values = self.map_ldap_attributes(cr, uid, conf, login, ldap_entry)
194 values['active'] = True
195 user_id = user_obj.copy(cr, SUPERUSER_ID, conf['user'],
198 user_id = user_obj.create(cr, SUPERUSER_ID, values)
202 'sequence': fields.integer('Sequence'),
203 'company': fields.many2one('res.company', 'Company', required=True,
205 'ldap_server': fields.char('LDAP Server address', size=64, required=True),
206 'ldap_server_port': fields.integer('LDAP Server port', required=True),
207 'ldap_binddn': fields.char('LDAP binddn', size=64,
208 help=("The user account on the LDAP server that is used to query "
209 "the directory. Leave empty to connect anonymously.")),
210 'ldap_password': fields.char('LDAP password', size=64,
211 help=("The password of the user account on the LDAP server that is "
212 "used to query the directory.")),
213 'ldap_filter': fields.char('LDAP filter', size=256, required=True),
214 'ldap_base': fields.char('LDAP base', size=64, required=True),
215 'user': fields.many2one('res.users', 'Template User',
216 help="User to copy when creating new users"),
217 'create_user': fields.boolean('Create user',
218 help="Automatically create local user accounts for new users authenticating via LDAP"),
219 'ldap_tls': fields.boolean('Use TLS',
220 help="Request secure TLS/SSL encryption when connecting to the LDAP server. "
221 "This option requires a server with STARTTLS enabled, "
222 "otherwise all authentication attempts will fail."),
225 'ldap_server': '127.0.0.1',
226 'ldap_server_port': 389,
233 class res_company(osv.osv):
234 _inherit = "res.company"
236 'ldaps': fields.one2many(
237 'res.company.ldap', 'company', 'LDAP Parameters'),
241 class users(osv.osv):
242 _inherit = "res.users"
243 def login(self, db, login, password):
244 user_id = super(users, self).login(db, login, password)
247 registry = RegistryManager.get(db)
248 with registry.cursor() as cr:
249 ldap_obj = registry.get('res.company.ldap')
250 for conf in ldap_obj.get_ldap_dicts(cr):
251 entry = ldap_obj.authenticate(conf, login, password)
253 user_id = ldap_obj.get_or_create_user(
254 cr, SUPERUSER_ID, conf, login, entry)
259 def check_credentials(self, cr, uid, password):
261 super(users, self).check_credentials(cr, uid, password)
262 except openerp.exceptions.AccessDenied:
264 cr.execute('SELECT login FROM res_users WHERE id=%s AND active=TRUE',
268 ldap_obj = self.pool['res.company.ldap']
269 for conf in ldap_obj.get_ldap_dicts(cr):
270 if ldap_obj.authenticate(conf, res[0], password):
274 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: