f4a985280ac9fa9f056838c038cccbeaeeb171a7
[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.osv import osv, fields
27 from openerp.tools.misc import DEFAULT_SERVER_DATETIME_FORMAT
28 from openerp.tools.safe_eval import safe_eval
29 from openerp.tools.translate import _
30
31 class SignupError(Exception):
32     pass
33
34 def random_token():
35     # the token has an entropy of about 120 bits (6 bits/char * 20 chars)
36     chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
37     return ''.join(random.choice(chars) for i in xrange(20))
38
39 def now(**kwargs):
40     dt = datetime.now() + timedelta(**kwargs)
41     return dt.strftime(DEFAULT_SERVER_DATETIME_FORMAT)
42
43
44 class res_partner(osv.Model):
45     _inherit = 'res.partner'
46
47     def _get_signup_valid(self, cr, uid, ids, name, arg, context=None):
48         dt = now()
49         res = {}
50         for partner in self.browse(cr, uid, ids, context):
51             res[partner.id] = bool(partner.signup_token) and \
52                                 (not partner.signup_expiration or dt <= partner.signup_expiration)
53         return res
54
55     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):
56         """ generate a signup url for the given partner ids and action, possibly overriding
57             the url state components (menu_id, id, view_type) """
58         res = dict.fromkeys(ids, False)
59         base_url = self.pool.get('ir.config_parameter').get_param(cr, uid, 'web.base.url')
60         for partner in self.browse(cr, uid, ids, context):
61             # when required, make sure the partner has a valid signup token
62             if context and context.get('signup_valid') and not partner.user_ids:
63                 self.signup_prepare(cr, uid, [partner.id], context=context)
64                 partner.refresh()
65
66             # the parameters to encode for the query and fragment part of url
67             query = {'db': cr.dbname}
68             fragment = {'action': action, 'type': partner.signup_type}
69
70             if partner.signup_token:
71                 fragment['token'] = partner.signup_token
72             elif partner.user_ids:
73                 fragment['db'] = cr.dbname
74                 fragment['login'] = partner.user_ids[0].login
75             else:
76                 continue        # no signup token, no user, thus no signup url!
77
78             if view_type:
79                 fragment['view_type'] = view_type
80             if menu_id:
81                 fragment['menu_id'] = menu_id
82             if model:
83                 fragment['model'] = model
84             if res_id:
85                 fragment['id'] = res_id
86
87             res[partner.id] = urljoin(base_url, "?%s#%s" % (urlencode(query), urlencode(fragment)))
88
89         return res
90
91     def _get_signup_url(self, cr, uid, ids, name, arg, context=None):
92         """ proxy for function field towards actual implementation """
93         return self._get_signup_url_for_action(cr, uid, ids, context=context)
94
95     _columns = {
96         'signup_token': fields.char('Signup Token'),
97         'signup_type': fields.char('Signup Token Type'),
98         'signup_expiration': fields.datetime('Signup Expiration'),
99         'signup_valid': fields.function(_get_signup_valid, type='boolean', string='Signup Token is Valid'),
100         'signup_url': fields.function(_get_signup_url, type='char', string='Signup URL'),
101     }
102
103     def action_signup_prepare(self, cr, uid, ids, context=None):
104         return self.signup_prepare(cr, uid, ids, context=context)
105
106     def signup_prepare(self, cr, uid, ids, signup_type="signup", expiration=False, context=None):
107         """ generate a new token for the partners with the given validity, if necessary
108             :param expiration: the expiration datetime of the token (string, optional)
109         """
110         for partner in self.browse(cr, uid, ids, context):
111             if expiration or not partner.signup_valid:
112                 token = random_token()
113                 while self._signup_retrieve_partner(cr, uid, token, context=context):
114                     token = random_token()
115                 partner.write({'signup_token': token, 'signup_type': signup_type, 'signup_expiration': expiration})
116         return True
117
118     def _signup_retrieve_partner(self, cr, uid, token,
119             check_validity=False, raise_exception=False, context=None):
120         """ find the partner corresponding to a token, and possibly check its validity
121             :param token: the token to resolve
122             :param check_validity: if True, also check validity
123             :param raise_exception: if True, raise exception instead of returning False
124             :return: partner (browse record) or False (if raise_exception is False)
125         """
126         partner_ids = self.search(cr, uid, [('signup_token', '=', token)], context=context)
127         if not partner_ids:
128             if raise_exception:
129                 raise SignupError("Signup token '%s' is not valid" % token)
130             return False
131         partner = self.browse(cr, uid, partner_ids[0], context)
132         if check_validity and not partner.signup_valid:
133             if raise_exception:
134                 raise SignupError("Signup token '%s' is no longer valid" % token)
135             return False
136         return partner
137
138     def signup_retrieve_info(self, cr, uid, token, context=None):
139         """ retrieve the user info about the token
140             :return: a dictionary with the user information:
141                 - 'db': the name of the database
142                 - 'token': the token, if token is valid
143                 - 'name': the name of the partner, if token is valid
144                 - 'login': the user login, if the user already exists
145                 - 'email': the partner email, if the user does not exist
146         """
147         partner = self._signup_retrieve_partner(cr, uid, token, raise_exception=True, context=None)
148         res = {'db': cr.dbname}
149         if partner.signup_valid:
150             res['token'] = token
151             res['name'] = partner.name
152         if partner.user_ids:
153             res['login'] = partner.user_ids[0].login
154         else:
155             res['email'] = partner.email or ''
156         return res
157
158 class res_users(osv.Model):
159     _inherit = 'res.users'
160
161     def _get_state(self, cr, uid, ids, name, arg, context=None):
162         res = {}
163         for user in self.browse(cr, uid, ids, context):
164             res[user.id] = ('active' if user.login_date else 'new')
165         return res
166
167     _columns = {
168         'state': fields.function(_get_state, string='Status', type='selection',
169                     selection=[('new', 'Never Connected'), ('active', 'Activated')]),
170     }
171
172     def signup(self, cr, uid, values, token=None, context=None):
173         """ signup a user, to either:
174             - create a new user (no token), or
175             - create a user for a partner (with token, but no user for partner), or
176             - change the password of a user (with token, and existing user).
177             :param values: a dictionary with field values that are written on user
178             :param token: signup token (optional)
179             :return: (dbname, login, password) for the signed up user
180         """
181         if token:
182             # signup with a token: find the corresponding partner id
183             res_partner = self.pool.get('res.partner')
184             partner = res_partner._signup_retrieve_partner(
185                             cr, uid, token, check_validity=True, raise_exception=True, context=None)
186             # invalidate signup token
187             partner.write({'signup_token': False, 'signup_type': False, 'signup_expiration': False})
188
189             partner_user = partner.user_ids and partner.user_ids[0] or False
190             if partner_user:
191                 # user exists, modify it according to values
192                 values.pop('login', None)
193                 values.pop('name', None)
194                 partner_user.write(values)
195                 return (cr.dbname, partner_user.login, values.get('password'))
196             else:
197                 # user does not exist: sign up invited user
198                 values.update({
199                     'name': partner.name,
200                     'partner_id': partner.id,
201                     'email': values.get('email') or values.get('login'),
202                 })
203                 if partner.company_id:
204                     values['company_id'] = partner.company_id.id
205                     values['company_ids'] = [(6,0,[partner.company_id.id])]
206                 self._signup_create_user(cr, uid, values, context=context)
207         else:
208             # no token, sign up an external user
209             values['email'] = values.get('email') or values.get('login')
210             self._signup_create_user(cr, uid, values, context=context)
211
212         return (cr.dbname, values.get('login'), values.get('password'))
213
214     def _signup_create_user(self, cr, uid, values, context=None):
215         """ create a new user from the template user """
216         ir_config_parameter = self.pool.get('ir.config_parameter')
217         template_user_id = safe_eval(ir_config_parameter.get_param(cr, uid, 'auth_signup.template_user_id', 'False'))
218         assert template_user_id and self.exists(cr, uid, template_user_id, context=context), 'Signup: invalid template user'
219
220         # check that uninvited users may sign up
221         if 'partner_id' not in values:
222             if not safe_eval(ir_config_parameter.get_param(cr, uid, 'auth_signup.allow_uninvited', 'False')):
223                 raise SignupError('Signup is not allowed for uninvited users')
224
225         assert values.get('login'), "Signup: no login given for new user"
226         assert values.get('partner_id') or values.get('name'), "Signup: no name or partner given for new user"
227
228         # create a copy of the template user (attached to a specific partner_id if given)
229         values['active'] = True
230         return self.copy(cr, uid, template_user_id, values, context=context)
231
232     def reset_password(self, cr, uid, login, context=None):
233         """ retrieve the user corresponding to login (login or email),
234             and reset their password
235         """
236         user_ids = self.search(cr, uid, [('login', '=', login)], context=context)
237         if not user_ids:
238             user_ids = self.search(cr, uid, [('email', '=', login)], context=context)
239         if len(user_ids) != 1:
240             raise Exception('Reset password: invalid username or email')
241         return self.action_reset_password(cr, uid, user_ids, context=context)
242
243     def action_reset_password(self, cr, uid, ids, context=None):
244         """ create signup token for each user, and send their signup url by email """
245         # prepare reset password signup
246         res_partner = self.pool.get('res.partner')
247         partner_ids = [user.partner_id.id for user in self.browse(cr, uid, ids, context)]
248         res_partner.signup_prepare(cr, uid, partner_ids, signup_type="reset", expiration=now(days=+1), context=context)
249
250         if not context:
251             context = {}
252
253         # send email to users with their signup url
254         template = False
255         if context.get('create_user'):
256             try:
257                 template = self.pool.get('ir.model.data').get_object(cr, uid, 'auth_signup', 'set_password_email')
258             except ValueError:
259                 pass
260         if not bool(template):
261             template = self.pool.get('ir.model.data').get_object(cr, uid, 'auth_signup', 'reset_password_email')
262         mail_obj = self.pool.get('mail.mail')
263         assert template._name == 'email.template'
264
265         for user in self.browse(cr, uid, ids, context):
266             if not user.email:
267                 raise osv.except_osv(_("Cannot send email: user has no email address."), user.name)
268             mail_id = self.pool.get('email.template').send_mail(cr, uid, template.id, user.id, True, context=context)
269             mail_state = mail_obj.read(cr, uid, mail_id, ['state'], context=context)
270
271             if mail_state and mail_state['state'] == 'exception':
272                 raise self.pool.get('res.config.settings').get_config_warning(cr, _("Cannot send email: no outgoing email server configured.\nYou can configure it under %(menu:base_setup.menu_general_configuration)s."), context)
273             else:
274                 return True
275
276     def create(self, cr, uid, values, context=None):
277         # overridden to automatically invite user to sign up
278         user_id = super(res_users, self).create(cr, uid, values, context=context)
279         user = self.browse(cr, uid, user_id, context=context)
280         if context and context.get('reset_password') and user.email:
281             ctx = dict(context, create_user=True)
282             self.action_reset_password(cr, uid, [user.id], context=ctx)
283         return user_id