[MERGE] with trunk
[odoo/odoo.git] / addons / auth_ldap / users_ldap.py
1 ##############################################################################
2 #    
3 #    OpenERP, Open Source Management Solution
4 #    Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
5 #
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.
10 #
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.
15 #
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/>.     
18 #
19 ##############################################################################
20
21 import ldap
22 import logging
23 from ldap.filter import filter_format
24
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__)
30
31 class CompanyLDAP(osv.osv):
32     _name = 'res.company.ldap'
33     _order = 'sequence'
34     _rec_name = 'ldap_server'
35
36     def get_ldap_dicts(self, cr, ids=None):
37         """ 
38         Retrieve res_company_ldap resources from the database in dictionary
39         format.
40
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
45         """
46
47         if ids:
48             id_clause = 'AND id IN (%s)'
49             args = [tuple(ids)]
50         else:
51             id_clause = ''
52             args = []
53         cr.execute("""
54             SELECT id, company, ldap_server, ldap_server_port, ldap_binddn,
55                    ldap_password, ldap_filter, ldap_base, "user", create_user,
56                    ldap_tls
57             FROM res_company_ldap
58             WHERE ldap_server != '' """ + id_clause + """ ORDER BY sequence
59         """, args)
60         return cr.dictfetchall()
61
62     def connect(self, conf):
63         """ 
64         Connect to an LDAP server specified by an ldap
65         configuration dictionary.
66
67         :param dict conf: LDAP configuration
68         :return: an LDAP object
69         """
70
71         uri = 'ldap://%s:%d' % (conf['ldap_server'],
72                                 conf['ldap_server_port'])
73
74         connection = ldap.initialize(uri)
75         if conf['ldap_tls']:
76             connection.start_tls_s()
77         return connection
78
79     def authenticate(self, conf, login, password):
80         """
81         Authenticate a user against the specified LDAP server.
82
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`)
86         
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
92         """
93
94         if not password:
95             return False
96
97         entry = False
98         filter = filter_format(conf['ldap_filter'], (login,))
99         try:
100             results = self.query(conf, filter)
101             if results and len(results) == 1:
102                 dn = results[0][0]
103                 conn = self.connect(conf)
104                 conn.simple_bind_s(dn, password)
105                 conn.unbind()
106                 entry = results[0]
107         except ldap.INVALID_CREDENTIALS:
108             return False
109         except ldap.LDAPError, e:
110             _logger.error('An LDAP exception occurred: %s', e)
111         return entry
112         
113     def query(self, conf, filter, retrieve_attributes=None):
114         """ 
115         Query an LDAP server with the filter argument and scope subtree.
116
117         Allow for all authentication methods of the simple authentication
118         method:
119
120         - authenticated bind (non-empty binddn + valid password)
121         - anonymous bind (empty binddn + empty password)
122         - unauthenticated authentication (non-empty binddn + empty password)
123
124         .. seealso::
125            :rfc:`4513#section-5.1` - LDAP: Simple Authentication Method.
126
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)
133
134         """
135
136         results = []
137         try:
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)
143             conn.unbind()
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)
148         return results
149
150     def map_ldap_attributes(self, cr, uid, conf, login, ldap_entry):
151         """
152         Compose values for a new resource of model res_users,
153         based upon the retrieved ldap entry and the LDAP settings.
154         
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
159         :rtype: dict
160         """
161
162         values = { 'name': ldap_entry[1]['cn'][0],
163                    'login': login,
164                    'company_id': conf['company']
165                    }
166         return values
167     
168     def get_or_create_user(self, cr, uid, conf, login, ldap_entry,
169                            context=None):
170         """
171         Retrieve an active resource of model res_users with the specified
172         login. Create the user if it is not initially found.
173
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
178         :rtype: int
179         """
180         
181         user_id = False
182         login = tools.ustr(login.lower())
183         cr.execute("SELECT id, active FROM res_users WHERE lower(login)=%s", (login,))
184         res = cr.fetchone()
185         if res:
186             if res[1]:
187                 user_id = res[0]
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)
192             if conf['user']:
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)
196             else:
197                 user_id = user_obj.create(cr, SUPERUSER_ID, values)
198         return user_id
199
200     _columns = {
201         'sequence': fields.integer('Sequence'),
202         'company': fields.many2one('res.company', 'Company', required=True,
203             ondelete='cascade'),
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."),
222     }
223     _defaults = {
224         'ldap_server': '127.0.0.1',
225         'ldap_server_port': 389,
226         'sequence': 10,
227         'create_user': True,
228     }
229
230
231
232 class res_company(osv.osv):
233     _inherit = "res.company"
234     _columns = {
235         'ldaps': fields.one2many(
236             'res.company.ldap', 'company', 'LDAP Parameters'),
237     }
238
239
240 class users(osv.osv):
241     _inherit = "res.users"
242     def login(self, db, login, password):
243         user_id = super(users, self).login(db, login, password)
244         if user_id:
245             return user_id
246         cr = self.pool.db.cursor()
247         ldap_obj = self.pool['res.company.ldap']
248         for conf in ldap_obj.get_ldap_dicts(cr):
249             entry = ldap_obj.authenticate(conf, login, password)
250             if entry:
251                 user_id = ldap_obj.get_or_create_user(
252                     cr, SUPERUSER_ID, conf, login, entry)
253                 if user_id:
254                     cr.execute("""UPDATE res_users
255                                     SET login_date=now() AT TIME ZONE 'UTC'
256                                     WHERE login=%s""",
257                                (tools.ustr(login),))
258                     cr.commit()
259                     break
260         cr.close()
261         return user_id
262
263     def check(self, db, uid, passwd):
264         try:
265             return super(users,self).check(db, uid, passwd)
266         except openerp.exceptions.AccessDenied:
267             pass
268
269         cr = self.pool.db.cursor()
270         cr.execute('SELECT login FROM res_users WHERE id=%s AND active=TRUE',
271                    (int(uid),))
272         res = cr.fetchone()
273         if res:
274             ldap_obj = self.pool['res.company.ldap']
275             for conf in ldap_obj.get_ldap_dicts(cr):
276                 if ldap_obj.authenticate(conf, res[0], passwd):
277                     self._uid_cache.setdefault(db, {})[uid] = passwd
278                     cr.close()
279                     return True
280         cr.close()
281         raise openerp.exceptions.AccessDenied()
282         
283 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: