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 _logger = logging.getLogger(__name__)
31 class CompanyLDAP(osv.osv):
32 _name = 'res.company.ldap'
34 _rec_name = 'ldap_server'
36 def get_ldap_dicts(self, cr, ids=None):
38 Retrieve res_company_ldap resources from the database in dictionary
41 :param list ids: Valid ids of model res_company_ldap. If not \
42 specified, process all resources (unlike other ORM methods).
43 :return: ldap configurations
44 :rtype: list of dictionaries
48 id_clause = 'AND id IN (%s)'
54 SELECT id, company, ldap_server, ldap_server_port, ldap_binddn,
55 ldap_password, ldap_filter, ldap_base, "user", create_user,
58 WHERE ldap_server != '' """ + id_clause + """ ORDER BY sequence
60 return cr.dictfetchall()
62 def connect(self, conf):
64 Connect to an LDAP server specified by an ldap
65 configuration dictionary.
67 :param dict conf: LDAP configuration
68 :return: an LDAP object
71 uri = 'ldap://%s:%d' % (conf['ldap_server'],
72 conf['ldap_server_port'])
74 connection = ldap.initialize(uri)
76 connection.start_tls_s()
79 def authenticate(self, conf, login, password):
81 Authenticate a user against the specified LDAP server.
83 In order to prevent an unintended 'unauthenticated authentication',
84 which is an anonymous bind with a valid dn and a blank password,
85 check for empty passwords explicitely (:rfc:`4513#section-6.3.1`)
87 :param dict conf: LDAP configuration
88 :param login: username
89 :param password: Password for the LDAP user
90 :return: LDAP entry of authenticated user or False
91 :rtype: dictionary of attributes
98 filter = filter_format(conf['ldap_filter'], (login,))
100 results = self.query(conf, filter)
101 if results and len(results) == 1:
103 conn = self.connect(conf)
104 conn.simple_bind_s(dn, password)
107 except ldap.INVALID_CREDENTIALS:
109 except ldap.LDAPError, e:
110 _logger.error('An LDAP exception occurred: %s', e)
113 def query(self, conf, filter, retrieve_attributes=None):
115 Query an LDAP server with the filter argument and scope subtree.
117 Allow for all authentication methods of the simple authentication
120 - authenticated bind (non-empty binddn + valid password)
121 - anonymous bind (empty binddn + empty password)
122 - unauthenticated authentication (non-empty binddn + empty password)
125 :rfc:`4513#section-5.1` - LDAP: Simple Authentication Method.
127 :param dict conf: LDAP configuration
128 :param filter: valid LDAP filter
129 :param list retrieve_attributes: LDAP attributes to be retrieved. \
130 If not specified, return all attributes.
131 :return: ldap entries
132 :rtype: list of tuples (dn, attrs)
138 conn = self.connect(conf)
139 conn.simple_bind_s(conf['ldap_binddn'] or '',
140 conf['ldap_password'] or '')
141 results = conn.search_st(conf['ldap_base'], ldap.SCOPE_SUBTREE,
142 filter, retrieve_attributes, timeout=60)
144 except ldap.INVALID_CREDENTIALS:
145 _logger.error('LDAP bind failed.')
146 except ldap.LDAPError, e:
147 _logger.error('An LDAP exception occurred: %s', e)
150 def map_ldap_attributes(self, cr, uid, conf, login, ldap_entry):
152 Compose values for a new resource of model res_users,
153 based upon the retrieved ldap entry and the LDAP settings.
155 :param dict conf: LDAP configuration
156 :param login: the new user's login
157 :param tuple ldap_entry: single LDAP result (dn, attrs)
158 :return: parameters for a new resource of model res_users
162 values = { 'name': ldap_entry[1]['cn'][0],
164 'company_id': conf['company']
168 def get_or_create_user(self, cr, uid, conf, login, ldap_entry,
171 Retrieve an active resource of model res_users with the specified
172 login. Create the user if it is not initially found.
174 :param dict conf: LDAP configuration
175 :param login: the user's login
176 :param tuple ldap_entry: single LDAP result (dn, attrs)
177 :return: res_users id
182 login = tools.ustr(login.lower())
183 cr.execute("SELECT id, active FROM res_users WHERE lower(login)=%s", (login,))
188 elif conf['create_user']:
189 _logger.debug("Creating new OpenERP user \"%s\" from LDAP" % login)
190 user_obj = self.pool['res.users']
191 values = self.map_ldap_attributes(cr, uid, conf, login, ldap_entry)
193 user_id = user_obj.copy(cr, SUPERUSER_ID, conf['user'],
194 default={'active': True})
195 user_obj.write(cr, SUPERUSER_ID, user_id, values)
197 user_id = user_obj.create(cr, SUPERUSER_ID, values)
201 'sequence': fields.integer('Sequence'),
202 'company': fields.many2one('res.company', 'Company', required=True,
204 'ldap_server': fields.char('LDAP Server address', size=64, required=True),
205 'ldap_server_port': fields.integer('LDAP Server port', required=True),
206 'ldap_binddn': fields.char('LDAP binddn', size=64,
207 help=("The user account on the LDAP server that is used to query "
208 "the directory. Leave empty to connect anonymously.")),
209 'ldap_password': fields.char('LDAP password', size=64,
210 help=("The password of the user account on the LDAP server that is "
211 "used to query the directory.")),
212 'ldap_filter': fields.char('LDAP filter', size=256, required=True),
213 'ldap_base': fields.char('LDAP base', size=64, required=True),
214 'user': fields.many2one('res.users', 'Template User',
215 help="User to copy when creating new users"),
216 'create_user': fields.boolean('Create user',
217 help="Automatically create local user accounts for new users authenticating via LDAP"),
218 'ldap_tls': fields.boolean('Use TLS',
219 help="Request secure TLS/SSL encryption when connecting to the LDAP server. "
220 "This option requires a server with STARTTLS enabled, "
221 "otherwise all authentication attempts will fail."),
224 'ldap_server': '127.0.0.1',
225 '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'),
242 class users(osv.osv):
243 _inherit = "res.users"
244 def login(self, db, login, password):
245 user_id = super(users, self).login(db, login, password)
248 cr = self.pool.db.cursor()
249 ldap_obj = self.pool['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)
256 cr.execute("""UPDATE res_users
257 SET login_date=now() AT TIME ZONE 'UTC'
259 (tools.ustr(login),))
265 def check(self, db, uid, passwd):
267 return super(users,self).check(db, uid, passwd)
268 except openerp.exceptions.AccessDenied:
271 cr = self.pool.db.cursor()
272 cr.execute('SELECT login FROM res_users WHERE id=%s AND active=TRUE',
276 ldap_obj = self.pool['res.company.ldap']
277 for conf in ldap_obj.get_ldap_dicts(cr):
278 if ldap_obj.authenticate(conf, res[0], passwd):
279 self._uid_cache.setdefault(db, {})[uid] = passwd
283 raise openerp.exceptions.AccessDenied()
286 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: