[FIX] /web/login restore request.uid in case of authentication failure
[odoo/odoo.git] / addons / auth_signup / res_users.py
1 # -*- coding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2012-today OpenERP SA (<http://www.openerp.com>)
6 #
7 #    This program is free software: you can redistribute it and/or modify
8 #    it under the terms of the GNU Affero General Public License as
9 #    published by the Free Software Foundation, either version 3 of the
10 #    License, or (at your option) any later version
11 #
12 #    This program is distributed in the hope that it will be useful,
13 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
14 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 #    GNU Affero General Public License for more details
16 #
17 #    You should have received a copy of the GNU Affero General Public License
18 #    along with this program.  If not, see <http://www.gnu.org/licenses/>
19 #
20 ##############################################################################
21 from datetime import datetime, timedelta
22 import random
23 from urlparse import urljoin
24 import werkzeug
25
26 from openerp.addons.base.ir.ir_mail_server import MailDeliveryException
27 from openerp.osv import osv, fields
28 from openerp.tools.misc import DEFAULT_SERVER_DATETIME_FORMAT, ustr
29 from ast import literal_eval
30 from openerp.tools.translate import _
31
32 class SignupError(Exception):
33     pass
34
35 def random_token():
36     # the token has an entropy of about 120 bits (6 bits/char * 20 chars)
37     chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
38     return ''.join(random.choice(chars) for i in xrange(20))
39
40 def now(**kwargs):
41     dt = datetime.now() + timedelta(**kwargs)
42     return dt.strftime(DEFAULT_SERVER_DATETIME_FORMAT)
43
44
45 class res_partner(osv.Model):
46     _inherit = 'res.partner'
47
48     def _get_signup_valid(self, cr, uid, ids, name, arg, context=None):
49         dt = now()
50         res = {}
51         for partner in self.browse(cr, uid, ids, context):
52             res[partner.id] = bool(partner.signup_token) and \
53                                 (not partner.signup_expiration or dt <= partner.signup_expiration)
54         return res
55
56     def _get_signup_url_for_action(self, cr, uid, ids, action=None, view_type=None, menu_id=None, res_id=None, model=None, context=None):
57         """ generate a signup url for the given partner ids and action, possibly overriding
58             the url state components (menu_id, id, view_type) """
59         if context is None:
60             context= {}
61         res = dict.fromkeys(ids, False)
62         base_url = self.pool.get('ir.config_parameter').get_param(cr, uid, 'web.base.url')
63         for partner in self.browse(cr, uid, ids, context):
64             # when required, make sure the partner has a valid signup token
65             if context.get('signup_valid') and not partner.user_ids:
66                 self.signup_prepare(cr, uid, [partner.id], context=context)
67                 partner.refresh()
68
69             route = 'login'
70             # the parameters to encode for the query
71             query = dict(db=cr.dbname)
72             signup_type = context.get('signup_force_type_in_url', partner.signup_type or '')
73             if signup_type:
74                 route = 'reset_password' if signup_type == 'reset' else signup_type
75
76             if partner.signup_token and signup_type:
77                 query['token'] = partner.signup_token
78             elif partner.user_ids:
79                 query['login'] = partner.user_ids[0].login
80             else:
81                 continue        # no signup token, no user, thus no signup url!
82
83             fragment = dict()
84             if action:
85                 fragment['action'] = action
86             if view_type:
87                 fragment['view_type'] = view_type
88             if menu_id:
89                 fragment['menu_id'] = menu_id
90             if model:
91                 fragment['model'] = model
92             if res_id:
93                 fragment['id'] = res_id
94
95             if fragment:
96                 query['redirect'] = '/web#' + werkzeug.url_encode(fragment)
97
98             res[partner.id] = urljoin(base_url, "/web/%s?%s" % (route, werkzeug.url_encode(query)))
99
100         return res
101
102     def _get_signup_url(self, cr, uid, ids, name, arg, context=None):
103         """ proxy for function field towards actual implementation """
104         return self._get_signup_url_for_action(cr, uid, ids, context=context)
105
106     _columns = {
107         'signup_token': fields.char('Signup Token'),
108         'signup_type': fields.char('Signup Token Type'),
109         'signup_expiration': fields.datetime('Signup Expiration'),
110         'signup_valid': fields.function(_get_signup_valid, type='boolean', string='Signup Token is Valid'),
111         'signup_url': fields.function(_get_signup_url, type='char', string='Signup URL'),
112     }
113
114     def action_signup_prepare(self, cr, uid, ids, context=None):
115         return self.signup_prepare(cr, uid, ids, context=context)
116
117     def signup_cancel(self, cr, uid, ids, context=None):
118         return self.write(cr, uid, ids, {'signup_token': False, 'signup_type': False, 'signup_expiration': False}, context=context)
119
120     def signup_prepare(self, cr, uid, ids, signup_type="signup", expiration=False, context=None):
121         """ generate a new token for the partners with the given validity, if necessary
122             :param expiration: the expiration datetime of the token (string, optional)
123         """
124         for partner in self.browse(cr, uid, ids, context):
125             if expiration or not partner.signup_valid:
126                 token = random_token()
127                 while self._signup_retrieve_partner(cr, uid, token, context=context):
128                     token = random_token()
129                 partner.write({'signup_token': token, 'signup_type': signup_type, 'signup_expiration': expiration})
130         return True
131
132     def _signup_retrieve_partner(self, cr, uid, token,
133             check_validity=False, raise_exception=False, context=None):
134         """ find the partner corresponding to a token, and possibly check its validity
135             :param token: the token to resolve
136             :param check_validity: if True, also check validity
137             :param raise_exception: if True, raise exception instead of returning False
138             :return: partner (browse record) or False (if raise_exception is False)
139         """
140         partner_ids = self.search(cr, uid, [('signup_token', '=', token)], context=context)
141         if not partner_ids:
142             if raise_exception:
143                 raise SignupError("Signup token '%s' is not valid" % token)
144             return False
145         partner = self.browse(cr, uid, partner_ids[0], context)
146         if check_validity and not partner.signup_valid:
147             if raise_exception:
148                 raise SignupError("Signup token '%s' is no longer valid" % token)
149             return False
150         return partner
151
152     def signup_retrieve_info(self, cr, uid, token, context=None):
153         """ retrieve the user info about the token
154             :return: a dictionary with the user information:
155                 - 'db': the name of the database
156                 - 'token': the token, if token is valid
157                 - 'name': the name of the partner, if token is valid
158                 - 'login': the user login, if the user already exists
159                 - 'email': the partner email, if the user does not exist
160         """
161         partner = self._signup_retrieve_partner(cr, uid, token, raise_exception=True, context=None)
162         res = {'db': cr.dbname}
163         if partner.signup_valid:
164             res['token'] = token
165             res['name'] = partner.name
166         if partner.user_ids:
167             res['login'] = partner.user_ids[0].login
168         else:
169             res['email'] = partner.email or ''
170         return res
171
172 class res_users(osv.Model):
173     _inherit = 'res.users'
174
175     def _get_state(self, cr, uid, ids, name, arg, context=None):
176         res = {}
177         for user in self.browse(cr, uid, ids, context):
178             res[user.id] = ('active' if user.login_date else 'new')
179         return res
180
181     _columns = {
182         'state': fields.function(_get_state, string='Status', type='selection',
183                     selection=[('new', 'Never Connected'), ('active', 'Activated')]),
184     }
185
186     def signup(self, cr, uid, values, token=None, context=None):
187         """ signup a user, to either:
188             - create a new user (no token), or
189             - create a user for a partner (with token, but no user for partner), or
190             - change the password of a user (with token, and existing user).
191             :param values: a dictionary with field values that are written on user
192             :param token: signup token (optional)
193             :return: (dbname, login, password) for the signed up user
194         """
195         if token:
196             # signup with a token: find the corresponding partner id
197             res_partner = self.pool.get('res.partner')
198             partner = res_partner._signup_retrieve_partner(
199                             cr, uid, token, check_validity=True, raise_exception=True, context=None)
200             # invalidate signup token
201             partner.write({'signup_token': False, 'signup_type': False, 'signup_expiration': False})
202
203             partner_user = partner.user_ids and partner.user_ids[0] or False
204             if partner_user:
205                 # user exists, modify it according to values
206                 values.pop('login', None)
207                 values.pop('name', None)
208                 partner_user.write(values)
209                 return (cr.dbname, partner_user.login, values.get('password'))
210             else:
211                 # user does not exist: sign up invited user
212                 values.update({
213                     'name': partner.name,
214                     'partner_id': partner.id,
215                     'email': values.get('email') or values.get('login'),
216                 })
217                 if partner.company_id:
218                     values['company_id'] = partner.company_id.id
219                     values['company_ids'] = [(6, 0, [partner.company_id.id])]
220                 self._signup_create_user(cr, uid, values, context=context)
221         else:
222             # no token, sign up an external user
223             values['email'] = values.get('email') or values.get('login')
224             self._signup_create_user(cr, uid, values, context=context)
225
226         return (cr.dbname, values.get('login'), values.get('password'))
227
228     def _signup_create_user(self, cr, uid, values, context=None):
229         """ create a new user from the template user """
230         ir_config_parameter = self.pool.get('ir.config_parameter')
231         template_user_id = literal_eval(ir_config_parameter.get_param(cr, uid, 'auth_signup.template_user_id', 'False'))
232         assert template_user_id and self.exists(cr, uid, template_user_id, context=context), 'Signup: invalid template user'
233
234         # check that uninvited users may sign up
235         if 'partner_id' not in values:
236             if not literal_eval(ir_config_parameter.get_param(cr, uid, 'auth_signup.allow_uninvited', 'False')):
237                 raise SignupError('Signup is not allowed for uninvited users')
238
239         assert values.get('login'), "Signup: no login given for new user"
240         assert values.get('partner_id') or values.get('name'), "Signup: no name or partner given for new user"
241
242         # create a copy of the template user (attached to a specific partner_id if given)
243         values['active'] = True
244         context = dict(context or {}, no_reset_password=True)
245         try:
246             with cr.savepoint():
247                 return self.copy(cr, uid, template_user_id, values, context=context)
248         except Exception, e:
249             # copy may failed if asked login is not available.
250             raise SignupError(ustr(e))
251
252     def reset_password(self, cr, uid, login, context=None):
253         """ retrieve the user corresponding to login (login or email),
254             and reset their password
255         """
256         user_ids = self.search(cr, uid, [('login', '=', login)], context=context)
257         if not user_ids:
258             user_ids = self.search(cr, uid, [('email', '=', login)], context=context)
259         if len(user_ids) != 1:
260             raise Exception('Reset password: invalid username or email')
261         return self.action_reset_password(cr, uid, user_ids, context=context)
262
263     def action_reset_password(self, cr, uid, ids, context=None):
264         """ create signup token for each user, and send their signup url by email """
265         # prepare reset password signup
266         res_partner = self.pool.get('res.partner')
267         partner_ids = [user.partner_id.id for user in self.browse(cr, uid, ids, context)]
268         res_partner.signup_prepare(cr, uid, partner_ids, signup_type="reset", expiration=now(days=+1), context=context)
269
270         if not context:
271             context = {}
272
273         # send email to users with their signup url
274         template = False
275         if context.get('create_user'):
276             try:
277                 # get_object() raises ValueError if record does not exist
278                 template = self.pool.get('ir.model.data').get_object(cr, uid, 'auth_signup', 'set_password_email')
279             except ValueError:
280                 pass
281         if not bool(template):
282             template = self.pool.get('ir.model.data').get_object(cr, uid, 'auth_signup', 'reset_password_email')
283         assert template._name == 'email.template'
284
285         for user in self.browse(cr, uid, ids, context):
286             if not user.email:
287                 raise osv.except_osv(_("Cannot send email: user has no email address."), user.name)
288             self.pool.get('email.template').send_mail(cr, uid, template.id, user.id, force_send=True, raise_exception=True, context=context)
289
290     def create(self, cr, uid, values, context=None):
291         if context is None:
292             context = {}
293         # overridden to automatically invite user to sign up
294         user_id = super(res_users, self).create(cr, uid, values, context=context)
295         user = self.browse(cr, uid, user_id, context=context)
296         if user.email and not context.get('no_reset_password'):
297             context.update({'create_user': True})
298             try:
299                 self.action_reset_password(cr, uid, [user.id], context=context)
300             except MailDeliveryException:
301                 self.pool.get('res.partner').signup_cancel(cr, uid, [user.partner_id.id], context=context)
302         return user_id