[MERGE] Merge from trunk-wms-loconopreport-jco
[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 urllib import urlencode
24 from urlparse import urljoin
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='login', 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 view_type:
85                 fragment['view_type'] = view_type
86             if menu_id:
87                 fragment['menu_id'] = menu_id
88             if model:
89                 fragment['model'] = model
90             if res_id:
91                 fragment['id'] = res_id
92
93             res[partner.id] = urljoin(base_url, "/web/%s?%s#%s" % (route, urlencode(query), urlencode(fragment)))
94
95         return res
96
97     def _get_signup_url(self, cr, uid, ids, name, arg, context=None):
98         """ proxy for function field towards actual implementation """
99         return self._get_signup_url_for_action(cr, uid, ids, context=context)
100
101     _columns = {
102         'signup_token': fields.char('Signup Token'),
103         'signup_type': fields.char('Signup Token Type'),
104         'signup_expiration': fields.datetime('Signup Expiration'),
105         'signup_valid': fields.function(_get_signup_valid, type='boolean', string='Signup Token is Valid'),
106         'signup_url': fields.function(_get_signup_url, type='char', string='Signup URL'),
107     }
108
109     def action_signup_prepare(self, cr, uid, ids, context=None):
110         return self.signup_prepare(cr, uid, ids, context=context)
111
112     def signup_cancel(self, cr, uid, ids, context=None):
113         return self.write(cr, uid, ids, {'signup_token': False, 'signup_type': False, 'signup_expiration': False}, context=context)
114
115     def signup_prepare(self, cr, uid, ids, signup_type="signup", expiration=False, context=None):
116         """ generate a new token for the partners with the given validity, if necessary
117             :param expiration: the expiration datetime of the token (string, optional)
118         """
119         for partner in self.browse(cr, uid, ids, context):
120             if expiration or not partner.signup_valid:
121                 token = random_token()
122                 while self._signup_retrieve_partner(cr, uid, token, context=context):
123                     token = random_token()
124                 partner.write({'signup_token': token, 'signup_type': signup_type, 'signup_expiration': expiration})
125         return True
126
127     def _signup_retrieve_partner(self, cr, uid, token,
128             check_validity=False, raise_exception=False, context=None):
129         """ find the partner corresponding to a token, and possibly check its validity
130             :param token: the token to resolve
131             :param check_validity: if True, also check validity
132             :param raise_exception: if True, raise exception instead of returning False
133             :return: partner (browse record) or False (if raise_exception is False)
134         """
135         partner_ids = self.search(cr, uid, [('signup_token', '=', token)], context=context)
136         if not partner_ids:
137             if raise_exception:
138                 raise SignupError("Signup token '%s' is not valid" % token)
139             return False
140         partner = self.browse(cr, uid, partner_ids[0], context)
141         if check_validity and not partner.signup_valid:
142             if raise_exception:
143                 raise SignupError("Signup token '%s' is no longer valid" % token)
144             return False
145         return partner
146
147     def signup_retrieve_info(self, cr, uid, token, context=None):
148         """ retrieve the user info about the token
149             :return: a dictionary with the user information:
150                 - 'db': the name of the database
151                 - 'token': the token, if token is valid
152                 - 'name': the name of the partner, if token is valid
153                 - 'login': the user login, if the user already exists
154                 - 'email': the partner email, if the user does not exist
155         """
156         partner = self._signup_retrieve_partner(cr, uid, token, raise_exception=True, context=None)
157         res = {'db': cr.dbname}
158         if partner.signup_valid:
159             res['token'] = token
160             res['name'] = partner.name
161         if partner.user_ids:
162             res['login'] = partner.user_ids[0].login
163         else:
164             res['email'] = partner.email or ''
165         return res
166
167 class res_users(osv.Model):
168     _inherit = 'res.users'
169
170     def _get_state(self, cr, uid, ids, name, arg, context=None):
171         res = {}
172         for user in self.browse(cr, uid, ids, context):
173             res[user.id] = ('active' if user.login_date else 'new')
174         return res
175
176     _columns = {
177         'state': fields.function(_get_state, string='Status', type='selection',
178                     selection=[('new', 'Never Connected'), ('active', 'Activated')]),
179     }
180
181     def signup(self, cr, uid, values, token=None, context=None):
182         """ signup a user, to either:
183             - create a new user (no token), or
184             - create a user for a partner (with token, but no user for partner), or
185             - change the password of a user (with token, and existing user).
186             :param values: a dictionary with field values that are written on user
187             :param token: signup token (optional)
188             :return: (dbname, login, password) for the signed up user
189         """
190         if token:
191             # signup with a token: find the corresponding partner id
192             res_partner = self.pool.get('res.partner')
193             partner = res_partner._signup_retrieve_partner(
194                             cr, uid, token, check_validity=True, raise_exception=True, context=None)
195             # invalidate signup token
196             partner.write({'signup_token': False, 'signup_type': False, 'signup_expiration': False})
197
198             partner_user = partner.user_ids and partner.user_ids[0] or False
199             if partner_user:
200                 # user exists, modify it according to values
201                 values.pop('login', None)
202                 values.pop('name', None)
203                 partner_user.write(values)
204                 return (cr.dbname, partner_user.login, values.get('password'))
205             else:
206                 # user does not exist: sign up invited user
207                 values.update({
208                     'name': partner.name,
209                     'partner_id': partner.id,
210                     'email': values.get('email') or values.get('login'),
211                 })
212                 if partner.company_id:
213                     values['company_id'] = partner.company_id.id
214                     values['company_ids'] = [(6, 0, [partner.company_id.id])]
215                 self._signup_create_user(cr, uid, values, context=context)
216         else:
217             # no token, sign up an external user
218             values['email'] = values.get('email') or values.get('login')
219             self._signup_create_user(cr, uid, values, context=context)
220
221         return (cr.dbname, values.get('login'), values.get('password'))
222
223     def _signup_create_user(self, cr, uid, values, context=None):
224         """ create a new user from the template user """
225         ir_config_parameter = self.pool.get('ir.config_parameter')
226         template_user_id = literal_eval(ir_config_parameter.get_param(cr, uid, 'auth_signup.template_user_id', 'False'))
227         assert template_user_id and self.exists(cr, uid, template_user_id, context=context), 'Signup: invalid template user'
228
229         # check that uninvited users may sign up
230         if 'partner_id' not in values:
231             if not literal_eval(ir_config_parameter.get_param(cr, uid, 'auth_signup.allow_uninvited', 'False')):
232                 raise SignupError('Signup is not allowed for uninvited users')
233
234         assert values.get('login'), "Signup: no login given for new user"
235         assert values.get('partner_id') or values.get('name'), "Signup: no name or partner given for new user"
236
237         # create a copy of the template user (attached to a specific partner_id if given)
238         values['active'] = True
239         context = dict(context or {}, no_reset_password=True)
240         try:
241             with cr.savepoint():
242                 return self.copy(cr, uid, template_user_id, values, context=context)
243         except Exception, e:
244             # copy may failed if asked login is not available.
245             raise SignupError(ustr(e))
246
247     def reset_password(self, cr, uid, login, context=None):
248         """ retrieve the user corresponding to login (login or email),
249             and reset their password
250         """
251         user_ids = self.search(cr, uid, [('login', '=', login)], context=context)
252         if not user_ids:
253             user_ids = self.search(cr, uid, [('email', '=', login)], context=context)
254         if len(user_ids) != 1:
255             raise Exception('Reset password: invalid username or email')
256         return self.action_reset_password(cr, uid, user_ids, context=context)
257
258     def action_reset_password(self, cr, uid, ids, context=None):
259         """ create signup token for each user, and send their signup url by email """
260         # prepare reset password signup
261         res_partner = self.pool.get('res.partner')
262         partner_ids = [user.partner_id.id for user in self.browse(cr, uid, ids, context)]
263         res_partner.signup_prepare(cr, uid, partner_ids, signup_type="reset", expiration=now(days=+1), context=context)
264
265         if not context:
266             context = {}
267
268         # send email to users with their signup url
269         template = False
270         if context.get('create_user'):
271             try:
272                 # get_object() raises ValueError if record does not exist
273                 template = self.pool.get('ir.model.data').get_object(cr, uid, 'auth_signup', 'set_password_email')
274             except ValueError:
275                 pass
276         if not bool(template):
277             template = self.pool.get('ir.model.data').get_object(cr, uid, 'auth_signup', 'reset_password_email')
278         assert template._name == 'email.template'
279
280         for user in self.browse(cr, uid, ids, context):
281             if not user.email:
282                 raise osv.except_osv(_("Cannot send email: user has no email address."), user.name)
283             self.pool.get('email.template').send_mail(cr, uid, template.id, user.id, force_send=True, raise_exception=True, context=context)
284
285     def create(self, cr, uid, values, context=None):
286         if context is None:
287             context = {}
288         # overridden to automatically invite user to sign up
289         user_id = super(res_users, self).create(cr, uid, values, context=context)
290         user = self.browse(cr, uid, user_id, context=context)
291         if user.email and not context.get('no_reset_password'):
292             context.update({'create_user': True})
293             try:
294                 self.action_reset_password(cr, uid, [user.id], context=context)
295             except MailDeliveryException:
296                 self.pool.get('res.partner').signup_cancel(cr, uid, [user.partner_id.id], context=context)
297         return user_id