Launchpad automatic translations update.
[odoo/odoo.git] / addons / users_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 from osv import fields, osv
22 import pooler
23 import tools
24 from service import security
25 import ldap
26 from ldap.filter import filter_format
27
28
29 class CompanyLDAP(osv.osv):
30     _name = 'res.company.ldap'
31     _order = 'sequence'
32     _rec_name = 'ldap_server'
33     _columns = {
34         'sequence': fields.integer('Sequence'),
35         'company': fields.many2one('res.company', 'Company', required=True,
36             ondelete='cascade'),
37         'ldap_server': fields.char('LDAP Server address', size=64, required=True),
38         'ldap_server_port': fields.integer('LDAP Server port', required=True),
39         'ldap_binddn': fields.char('LDAP binddn', size=64, required=True),
40         'ldap_password': fields.char('LDAP password', size=64, required=True),
41         'ldap_filter': fields.char('LDAP filter', size=64, required=True),
42         'ldap_base': fields.char('LDAP base', size=64, required=True),
43         'user': fields.many2one('res.users', 'Model User',
44             help="Model used for user creation"),
45         'create_user': fields.boolean('Create user',
46             help="Create the user if not in database"),
47     }
48     _defaults = {
49         'ldap_server': lambda *a: '127.0.0.1',
50         'ldap_server_port': lambda *a: 389,
51         'sequence': lambda *a: 10,
52         'create_user': lambda *a: True,
53     }
54
55 CompanyLDAP()
56
57
58 class res_company(osv.osv):
59     _inherit = "res.company"
60     _columns = {
61         'ldaps': fields.one2many('res.company.ldap', 'company', 'LDAP Parameters'),
62     }
63 res_company()
64
65 class users(osv.osv):
66     _inherit = "res.users"
67     def login(self, db, login, password):
68         ret = super(users,self).login(db, login, password)
69         tools.debug(ret)
70         if ret:
71             return ret
72         pool = pooler.get_pool(db)
73         cr = pooler.get_db(db).cursor()
74         action_obj = pool.get('ir.actions.actions')
75         cr.execute("""
76             SELECT id, company, ldap_server, ldap_server_port, ldap_binddn, ldap_password,
77                    ldap_filter, ldap_base, "user", create_user
78             FROM res_company_ldap
79             WHERE ldap_server != '' and ldap_binddn != '' ORDER BY sequence""")
80         for res_company_ldap in cr.dictfetchall():
81             tools.debug(res_company_ldap)
82             try:
83                 l = ldap.open(res_company_ldap['ldap_server'], res_company_ldap['ldap_server_port'])
84                 if l.simple_bind_s(res_company_ldap['ldap_binddn'], res_company_ldap['ldap_password']):
85                     base = res_company_ldap['ldap_base']
86                     scope = ldap.SCOPE_SUBTREE
87                     filter = filter_format(res_company_ldap['ldap_filter'], (login,))
88                     retrieve_attributes = None
89                     result_id = l.search(base, scope, filter, retrieve_attributes)
90                     timeout = 60
91                     result_type, result_data = l.result(result_id, timeout)
92                     if not result_data:
93                         continue
94                     if result_type == ldap.RES_SEARCH_RESULT and len(result_data) == 1:
95                         dn = result_data[0][0]
96                         tools.debug(dn)
97                         name = result_data[0][1]['cn'][0]
98                         if l.bind_s(dn, password):
99                             l.unbind()
100                             cr.execute("SELECT id FROM res_users WHERE login=%s",(tools.ustr(login),))
101                             res = cr.fetchone()
102                             tools.debug(res)
103                             if res:
104                                 cr.close()
105                                 return res[0]
106                             if not res_company_ldap['create_user']:
107                                 continue
108                             action_id = action_obj.search(cr, 1, [('usage', '=', 'menu')])[0]
109                             if res_company_ldap['user']:
110                                 res = self.copy(cr, 1, res_company_ldap['user'],
111                                         default={'active': True})
112                                 self.write(cr, 1, res, {
113                                     'name': name,
114                                     'login': login.encode('utf-8'),
115                                     'company_id': res_company_ldap['company'],
116                                     })
117                             else:
118                                 res = self.create(cr, 1, {
119                                     'name': name,
120                                     'login': login.encode('utf-8'),
121                                     'company_id': res_company_ldap['company'],
122                                     'action_id': action_id,
123                                     'menu_id': action_id,
124                                     })
125                             cr.commit()
126                             cr.close()
127                             return res
128                     l.unbind()
129             except Exception, e:
130                 tools.debug(e)
131                 continue
132         cr.close()
133         return False
134
135     def check(self, db, uid, passwd):
136         try:
137             return super(users,self).check(db, uid, passwd)
138         except: # AccessDenied
139             pass
140         cr = pooler.get_db(db).cursor()
141         user = self.browse(cr, 1, uid)
142         if user and user.company_id.ldaps:
143             for res_company_ldap in user.company_id.ldaps:
144                 try:
145                     l = ldap.open(res_company_ldap.ldap_server, res_company_ldap.ldap_server_port)
146                     if l.simple_bind_s(res_company_ldap.ldap_binddn,
147                             res_company_ldap.ldap_password):
148                         base = res_company_ldap.ldap_base
149                         scope = ldap.SCOPE_SUBTREE
150                         filter = filter_format(res_company_ldap.ldap_filter, (user.login,))
151                         retrieve_attributes = None
152                         result_id = l.search(base, scope, filter, retrieve_attributes)
153                         timeout = 60
154                         result_type, result_data = l.result(result_id, timeout)
155                         if result_data and result_type == ldap.RES_SEARCH_RESULT and len(result_data) == 1:
156                             dn = result_data[0][0]
157                             if l.bind_s(dn, passwd):
158                                 l.unbind()
159                                 self._uid_cache.setdefault(db, {})[uid] = passwd
160                                 cr.close()
161                                 return True
162                         l.unbind()
163                 except Exception, e:
164                     tools.debug(e)
165                     pass
166         cr.close()
167         raise security.ExceptionNoTb('AccessDenied')
168         
169 users()
170 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
171