[IMP]Added referenced to published partners.
[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 from openerp.modules.registry import RegistryManager
30 _logger = logging.getLogger(__name__)
31
32 class CompanyLDAP(osv.osv):
33     _name = 'res.company.ldap'
34     _order = 'sequence'
35     _rec_name = 'ldap_server'
36
37     def get_ldap_dicts(self, cr, ids=None):
38         """ 
39         Retrieve res_company_ldap resources from the database in dictionary
40         format.
41
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
46         """
47
48         if ids:
49             id_clause = 'AND id IN (%s)'
50             args = [tuple(ids)]
51         else:
52             id_clause = ''
53             args = []
54         cr.execute("""
55             SELECT id, company, ldap_server, ldap_server_port, ldap_binddn,
56                    ldap_password, ldap_filter, ldap_base, "user", create_user,
57                    ldap_tls
58             FROM res_company_ldap
59             WHERE ldap_server != '' """ + id_clause + """ ORDER BY sequence
60         """, args)
61         return cr.dictfetchall()
62
63     def connect(self, conf):
64         """ 
65         Connect to an LDAP server specified by an ldap
66         configuration dictionary.
67
68         :param dict conf: LDAP configuration
69         :return: an LDAP object
70         """
71
72         uri = 'ldap://%s:%d' % (conf['ldap_server'],
73                                 conf['ldap_server_port'])
74
75         connection = ldap.initialize(uri)
76         if conf['ldap_tls']:
77             connection.start_tls_s()
78         return connection
79
80     def authenticate(self, conf, login, password):
81         """
82         Authenticate a user against the specified LDAP server.
83
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`)
87         
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
93         """
94
95         if not password:
96             return False
97
98         entry = False
99         filter = filter_format(conf['ldap_filter'], (login,))
100         try:
101             results = self.query(conf, filter)
102             if results and len(results) == 1:
103                 dn = results[0][0]
104                 conn = self.connect(conf)
105                 conn.simple_bind_s(dn, password)
106                 conn.unbind()
107                 entry = results[0]
108         except ldap.INVALID_CREDENTIALS:
109             return False
110         except ldap.LDAPError, e:
111             _logger.error('An LDAP exception occurred: %s', e)
112         return entry
113         
114     def query(self, conf, filter, retrieve_attributes=None):
115         """ 
116         Query an LDAP server with the filter argument and scope subtree.
117
118         Allow for all authentication methods of the simple authentication
119         method:
120
121         - authenticated bind (non-empty binddn + valid password)
122         - anonymous bind (empty binddn + empty password)
123         - unauthenticated authentication (non-empty binddn + empty password)
124
125         .. seealso::
126            :rfc:`4513#section-5.1` - LDAP: Simple Authentication Method.
127
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)
134
135         """
136
137         results = []
138         try:
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)
144             conn.unbind()
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)
149         return results
150
151     def map_ldap_attributes(self, cr, uid, conf, login, ldap_entry):
152         """
153         Compose values for a new resource of model res_users,
154         based upon the retrieved ldap entry and the LDAP settings.
155         
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
160         :rtype: dict
161         """
162
163         values = { 'name': ldap_entry[1]['cn'][0],
164                    'login': login,
165                    'company_id': conf['company']
166                    }
167         return values
168     
169     def get_or_create_user(self, cr, uid, conf, login, ldap_entry,
170                            context=None):
171         """
172         Retrieve an active resource of model res_users with the specified
173         login. Create the user if it is not initially found.
174
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
179         :rtype: int
180         """
181         
182         user_id = False
183         login = tools.ustr(login.lower())
184         cr.execute("SELECT id, active FROM res_users WHERE lower(login)=%s", (login,))
185         res = cr.fetchone()
186         if res:
187             if res[1]:
188                 user_id = res[0]
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)
193             if conf['user']:
194                 values['active'] = True
195                 user_id = user_obj.copy(cr, SUPERUSER_ID, conf['user'],
196                                         default=values)
197             else:
198                 user_id = user_obj.create(cr, SUPERUSER_ID, values)
199         return user_id
200
201     _columns = {
202         'sequence': fields.integer('Sequence'),
203         'company': fields.many2one('res.company', 'Company', required=True,
204             ondelete='cascade'),
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."),
223     }
224     _defaults = {
225         'ldap_server': '127.0.0.1',
226         'ldap_server_port': 389,
227         'sequence': 10,
228         'create_user': True,
229     }
230
231
232
233 class res_company(osv.osv):
234     _inherit = "res.company"
235     _columns = {
236         'ldaps': fields.one2many(
237             'res.company.ldap', 'company', 'LDAP Parameters'),
238     }
239
240
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)
245         if user_id:
246             return user_id
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)
252                 if entry:
253                     user_id = ldap_obj.get_or_create_user(
254                         cr, SUPERUSER_ID, conf, login, entry)
255                     if user_id:
256                         break
257             return user_id
258
259     def check_credentials(self, cr, uid, password):
260         try:
261             super(users, self).check_credentials(cr, uid, password)
262         except openerp.exceptions.AccessDenied:
263
264             cr.execute('SELECT login FROM res_users WHERE id=%s AND active=TRUE',
265                        (int(uid),))
266             res = cr.fetchone()
267             if res:
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):
271                         return
272             raise
273         
274 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: