~marrakis/openobject-server/python-lib

« back to all changes in this revision

Viewing changes to openobject/addons/base/res/res_user.py

  • Committer: Mathieu Leduc-Hamel
  • Date: 2010-02-11 20:36:24 UTC
  • Revision ID: mlhamel@arak4-20100211203624-4331pfj1xb8qtzw8
[IMP] New pythonic way to organise the code. Everything is under the package openobject.server and everything is refering to that. Now needed to clean again setup.py

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# -*- coding: utf-8 -*-
2
 
##############################################################################
3
 
#
4
 
#    OpenERP, Open Source Management Solution
5
 
#    Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
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
 
 
22
 
from openobject.osv import fields,osv
23
 
from openobject.osv.orm import except_orm
24
 
from openobject.service import security
25
 
from openobject.tools.translate import _
26
 
import openobject.config
27
 
import openobject.pooler
28
 
import openobject.tools.misc
29
 
import pytz
30
 
 
31
 
class groups(osv.osv):
32
 
    _name = "res.groups"
33
 
    _order = 'name'
34
 
    _columns = {
35
 
        'name': fields.char('Group Name', size=64, required=True),
36
 
        'model_access': fields.one2many('ir.model.access', 'group_id', 'Access Controls'),
37
 
        'rule_groups': fields.many2many('ir.rule.group', 'group_rule_group_rel',
38
 
            'group_id', 'rule_group_id', 'Rules', domain="[('global', '<>', True)]"),
39
 
        'menu_access': fields.many2many('ir.ui.menu', 'ir_ui_menu_group_rel', 'gid', 'menu_id', 'Access Menu'),
40
 
        'comment' : fields.text('Comment',size=250),
41
 
    }
42
 
    _sql_constraints = [
43
 
        ('name_uniq', 'unique (name)', 'The name of the group must be unique !')
44
 
    ]
45
 
    def copy(self, cr, uid, id, default=None, context={}):
46
 
        group_name = self.read(cr, uid, [id], ['name'])[0]['name']
47
 
        default.update({'name': group_name +' (copy)'})
48
 
        return super(groups, self).copy(cr, uid, id, default, context)
49
 
 
50
 
    def write(self, cr, uid, ids, vals, context=None):
51
 
        if 'name' in vals:
52
 
            if vals['name'].startswith('-'):
53
 
                raise osv.except_osv(_('Error'),
54
 
                        _('The name of the group can not start with "-"'))
55
 
        res = super(groups, self).write(cr, uid, ids, vals, context=context)
56
 
        # Restart the cache on the company_get method
57
 
        self.pool.get('ir.rule').domain_get.clear_cache(cr.dbname)
58
 
        self.pool.get('ir.model.access').call_cache_clearing_methods(cr)
59
 
        return res
60
 
 
61
 
    def create(self, cr, uid, vals, context=None):
62
 
        if 'name' in vals:
63
 
            if vals['name'].startswith('-'):
64
 
                raise osv.except_osv(_('Error'),
65
 
                        _('The name of the group can not start with "-"'))
66
 
        gid = super(groups, self).create(cr, uid, vals, context=context)
67
 
        if context and context.get('noadmin', False):
68
 
            pass
69
 
        else:
70
 
            # assign this new group to user_root
71
 
            user_obj = self.pool.get('res.users')
72
 
            aid = user_obj.browse(cr, 1, user_obj._get_admin_id(cr))
73
 
            if aid:
74
 
                aid.write({'groups_id': [(4, gid)]})
75
 
        return gid
76
 
 
77
 
    def copy(self, cr, uid, id, default={}, context={}, done_list=[], local=False):
78
 
        group = self.browse(cr, uid, id, context=context)
79
 
        default = default.copy()
80
 
        if not 'name' in default:
81
 
            default['name'] = group['name']
82
 
        default['name'] = default['name'] + _(' (copy)')
83
 
        return super(groups, self).copy(cr, uid, id, default, context=context)
84
 
 
85
 
groups()
86
 
 
87
 
 
88
 
class roles(osv.osv):
89
 
    _name = "res.roles"
90
 
    _columns = {
91
 
        'name': fields.char('Role Name', size=64, required=True),
92
 
        'parent_id': fields.many2one('res.roles', 'Parent', select=True),
93
 
        'child_id': fields.one2many('res.roles', 'parent_id', 'Children'),
94
 
        'users': fields.many2many('res.users', 'res_roles_users_rel', 'rid', 'uid', 'Users'),
95
 
    }
96
 
    _defaults = {
97
 
    }
98
 
    def check(self, cr, uid, ids, role_id):
99
 
        if role_id in ids:
100
 
            return True
101
 
        cr.execute('select parent_id from res_roles where id=%s', (role_id,))
102
 
        roles = cr.fetchone()[0]
103
 
        if roles:
104
 
            return self.check(cr, uid, ids, roles)
105
 
        return False
106
 
roles()
107
 
 
108
 
def _lang_get(self, cr, uid, context={}):
109
 
    obj = self.pool.get('res.lang')
110
 
    ids = obj.search(cr, uid, [])
111
 
    res = obj.read(cr, uid, ids, ['code', 'name'], context)
112
 
    res = [(r['code'], r['name']) for r in res]
113
 
    return res
114
 
def _tz_get(self,cr,uid, context={}):
115
 
    return [(x, x) for x in pytz.all_timezones]
116
 
 
117
 
def _companies_get(self,cr, uid, context={}):
118
 
    res=[]
119
 
    ids = self.pool.get('res.users').browse(cr, uid, uid, context).company_ids
120
 
    res = [(i.id,i.name) for i in ids]
121
 
    return res
122
 
 
123
 
class users(osv.osv):
124
 
    __admin_ids = {}
125
 
    _uid_cache = {}
126
 
    _name = "res.users"
127
 
 
128
 
    def get_current_company(self, cr, uid):
129
 
        res=[]
130
 
        cr.execute('select company_id, res_company.name from res_users left join res_company on res_company.id = company_id where res_users.id=%s' %uid)
131
 
        res = cr.fetchall()
132
 
        return res
133
 
 
134
 
    _columns = {
135
 
        'name': fields.char('Name', size=64, required=True, select=True),
136
 
        'login': fields.char('Login', size=64, required=True),
137
 
        'password': fields.char('Password', size=64, invisible=True, help="Keep empty if you don't want the user to be able to connect on the system."),
138
 
        'email': fields.char('E-mail', size=64, help='If an email is provided'\
139
 
                             ', the user will be sent a message welcoming him'),
140
 
        'signature': fields.text('Signature', size=64),
141
 
        'address_id': fields.many2one('res.partner.address', 'Address'),
142
 
        'active': fields.boolean('Active'),
143
 
        'action_id': fields.many2one('ir.actions.actions', 'Home Action'),
144
 
        'menu_id': fields.many2one('ir.actions.actions', 'Menu Action'),
145
 
        'groups_id': fields.many2many('res.groups', 'res_groups_users_rel', 'uid', 'gid', 'Groups'),
146
 
        'roles_id': fields.many2many('res.roles', 'res_roles_users_rel', 'uid', 'rid', 'Roles'),
147
 
        'rules_id': fields.many2many('ir.rule.group', 'user_rule_group_rel', 'user_id', 'rule_group_id', 'Rules'),
148
 
        'company_id': fields.many2one('res.company', 'Company', help="The company this user is currently working on.", required=True),
149
 
        'company_ids':fields.many2many('res.company','res_company_users_rel','user_id','cid','Accepted Companies'),
150
 
        'context_lang': fields.selection(_lang_get, 'Language', required=True),
151
 
        'context_tz': fields.selection(_tz_get,  'Timezone', size=64),
152
 
        'company': fields.selection(_companies_get,  'Company', size=64),
153
 
    }
154
 
    def read(self,cr, uid, ids, fields=None, context=None, load='_classic_read'):
155
 
        def override_password(o):
156
 
            if 'password' in o and ( 'id' not in o or o['id'] != uid ):
157
 
                o['password'] = '********'
158
 
            return o
159
 
 
160
 
        result = super(users, self).read(cr, uid, ids, fields, context, load)
161
 
        canwrite = self.pool.get('ir.model.access').check(cr, uid, 'res.users', 'write', raise_exception=False)
162
 
        if not canwrite:
163
 
            if isinstance(ids, (int, float)):
164
 
                result = override_password(result)
165
 
            else:
166
 
                result = map(override_password, result)
167
 
        return result
168
 
 
169
 
    _sql_constraints = [
170
 
        ('login_key', 'UNIQUE (login)',  _('You can not have two users with the same login !'))
171
 
    ]
172
 
 
173
 
    def _get_admin_id(self, cr):
174
 
        if self.__admin_ids.get(cr.dbname) is None:
175
 
            ir_model_data_obj = self.pool.get('ir.model.data')
176
 
            mdid = ir_model_data_obj._get_id(cr, 1, 'base', 'user_root')
177
 
            self.__admin_ids[cr.dbname] = ir_model_data_obj.read(cr, 1, [mdid], ['res_id'])[0]['res_id']
178
 
        return self.__admin_ids[cr.dbname]
179
 
 
180
 
    def _get_action(self,cr, uid, context={}):
181
 
        ids = self.pool.get('ir.ui.menu').search(cr, uid, [('usage','=','menu')])
182
 
        return ids and ids[0] or False
183
 
 
184
 
    def _get_company(self,cr, uid, context={}):
185
 
        return self.pool.get('res.users').browse(cr, uid, uid, context).company_id.id
186
 
 
187
 
    def _get_menu(self,cr, uid, context={}):
188
 
        ids = self.pool.get('ir.actions.act_window').search(cr, uid, [('usage','=','menu')])
189
 
        return ids and ids[0] or False
190
 
 
191
 
    def _get_group(self,cr, uid, context={}):
192
 
        ids = self.pool.get('res.groups').search(cr, uid, [('name','=','Employee')])
193
 
        return ids or False
194
 
 
195
 
    _defaults = {
196
 
        'password' : lambda *a : '',
197
 
        'context_lang': lambda *args: 'en_US',
198
 
        'active' : lambda *a: True,
199
 
        'menu_id': _get_menu,
200
 
        'action_id': _get_menu,
201
 
        'company_id': _get_company,
202
 
        'groups_id': _get_group,
203
 
        'address_id': False,
204
 
    }
205
 
    def company_get(self, cr, uid, uid2):
206
 
        company_id = self.pool.get('res.users').browse(cr, uid, uid2).company_id.id
207
 
        return company_id
208
 
    company_get = openobject.tools.misc.cache()(company_get)
209
 
 
210
 
    def write(self, cr, uid, ids, values, *args, **argv):
211
 
        if (ids == [uid]):
212
 
            ok = True
213
 
            for k in values.keys():
214
 
                if k not in ('password','signature','action_id', 'context_lang', 'context_tz','company_id'):
215
 
                    ok=False
216
 
            if ok:
217
 
                uid = 1
218
 
        res = super(users, self).write(cr, uid, ids, values, *args, **argv)
219
 
        self.company_get.clear_cache(cr.dbname)
220
 
        # Restart the cache on the company_get method
221
 
        self.pool.get('ir.rule').domain_get.clear_cache(cr.dbname)
222
 
        self.pool.get('ir.model.access').call_cache_clearing_methods(cr)
223
 
        return res
224
 
 
225
 
    def unlink(self, cr, uid, ids, context=None):
226
 
        if 1 in ids:
227
 
            raise osv.except_osv(_('Can not remove root user!'), _('You can not remove the admin user as it is used internally for resources created by OpenERP (updates, module installation, ...)'))
228
 
        return super(users, self).unlink(cr, uid, ids, context=context)
229
 
 
230
 
    def name_search(self, cr, user, name='', args=None, operator='ilike', context=None, limit=100):
231
 
        if not args:
232
 
            args=[]
233
 
        if not context:
234
 
            context={}
235
 
        ids = []
236
 
        if name:
237
 
            ids = self.search(cr, user, [('login','=',name)]+ args, limit=limit)
238
 
        if not ids:
239
 
            ids = self.search(cr, user, [('name',operator,name)]+ args, limit=limit)
240
 
        return self.name_get(cr, user, ids)
241
 
 
242
 
    def copy(self, cr, uid, id, default=None, context={}):
243
 
        login = self.read(cr, uid, [id], ['login'])[0]['login']
244
 
        default.update({'login': login+' (copy)'})
245
 
        return super(users, self).copy(cr, uid, id, default, context)
246
 
 
247
 
    def context_get(self, cr, uid, context=None):
248
 
        user = self.browse(cr, uid, uid, context)
249
 
        result = {}
250
 
        for k in self._columns.keys():
251
 
            if k.startswith('context_'):
252
 
                result[k[8:]] = getattr(user,k)
253
 
        return result
254
 
 
255
 
 
256
 
    def _check_company(self, cursor, user, ids):
257
 
        for user in self.browse(cursor, user, ids):
258
 
            if user.company_ids and (user.company_id.id not in map(lambda x: x.id, user.company_ids)):
259
 
                return False
260
 
        return True
261
 
 
262
 
    def action_get(self, cr, uid, context={}):
263
 
        dataobj = self.pool.get('ir.model.data')
264
 
        data_id = dataobj._get_id(cr, 1, 'base', 'action_res_users_my')
265
 
        return dataobj.browse(cr, uid, data_id, context).res_id
266
 
 
267
 
 
268
 
    def login(self, db, login, password):
269
 
        if not password:
270
 
            return False
271
 
        cr = openobject.pooler.get_db(db).cursor()
272
 
        cr.execute('select id from res_users where login=%s and password=%s and active',
273
 
                   (openobject.tools.misc.ustr(login), openobject.tools.misc.ustr(password)))
274
 
        res = cr.fetchone()
275
 
        cr.close()
276
 
        if res:
277
 
            return res[0]
278
 
        else:
279
 
            return False
280
 
 
281
 
    def check_super(self, passwd):
282
 
        if passwd == config.config['admin_passwd']:
283
 
            return True
284
 
        else:
285
 
            raise security.ExceptionNoTb('AccessDenied')
286
 
 
287
 
    def check(self, db, uid, passwd):
288
 
        if not passwd:
289
 
            return False
290
 
        cached_pass = self._uid_cache.get(db, {}).get(uid)
291
 
        if (cached_pass is not None) and cached_pass == passwd:
292
 
            return True
293
 
        cr = openobject.pooler.get_db(db).cursor()    
294
 
        cr.execute('select count(1) from res_users where id=%s and password=%s and active=%s', (int(uid), passwd, True))    
295
 
        res = cr.fetchone()[0]
296
 
        cr.close()
297
 
        if not bool(res):
298
 
            raise security.ExceptionNoTb('AccessDenied')
299
 
        if res:
300
 
            if self._uid_cache.has_key(db):
301
 
                ulist = self._uid_cache[db]
302
 
                ulist[uid] = passwd
303
 
            else:
304
 
                self._uid_cache[db] = {uid:passwd}
305
 
        return bool(res)
306
 
 
307
 
    def access(self, db, uid, passwd, sec_level, ids):
308
 
        if not passwd:
309
 
            return False
310
 
        cr = openobject.pooler.get_db(db).cursor()    
311
 
        cr.execute('select id from res_users where id=%s and password=%s', (uid, passwd))
312
 
        res = cr.fetchone()
313
 
        cr.close()
314
 
        if not res:
315
 
            raise security.ExceptionNoTb('Bad username or password')
316
 
        return res[0]
317
 
 
318
 
    _constraints = [
319
 
        (_check_company, 'This user can not connect using this company !', ['company_id']),
320
 
    ]
321
 
users()
322
 
 
323
 
class config_users(osv.osv_memory):
324
 
    _name = 'res.config.users'
325
 
    _inherit = ['res.users', 'res.config']
326
 
 
327
 
    def _generate_signature(self, cr, name, email, context=None):
328
 
        return _('--\n%(name)s %(email)s\n') % {
329
 
            'name': name or '',
330
 
            'email': email and ' <'+email+'>' or '',
331
 
            }
332
 
 
333
 
    def create_user(self, cr, uid, new_id, context=None):
334
 
        ''' create a new res.user instance from the data stored
335
 
        in the current res.config.users
336
 
        '''
337
 
        base_data = self.read(cr, uid, new_id, context=context)
338
 
        partner_id = self.pool.get('res.partner').main_partner(cr, uid)
339
 
        address = self.pool.get('res.partner.address').create(
340
 
            cr, uid, {'name': base_data['name'],
341
 
                      'email': base_data['email'],
342
 
                      'partner_id': partner_id,},
343
 
            context)
344
 
        user_data = dict(
345
 
            base_data,
346
 
            signature=self._generate_signature(
347
 
                cr, base_data['name'], base_data['email'], context=context),
348
 
            address_id=address,
349
 
            )
350
 
        self.pool.get('res.users').create(
351
 
            cr, uid, user_data, context)
352
 
 
353
 
    def execute(self, cr, uid, ids, context=None):
354
 
        self.create_user(cr, uid, ids[0], context=context)
355
 
        return {
356
 
            'view_type': 'form',
357
 
            "view_mode": 'form',
358
 
            'res_model': 'res.config.users',
359
 
            'view_id':self.pool.get('ir.ui.view')\
360
 
                .search(cr,uid,[('name','=','res.config.users.confirm.form')]),
361
 
            'type': 'ir.actions.act_window',
362
 
            'target':'new',
363
 
            }
364
 
config_users()
365
 
 
366
 
class groups2(osv.osv): ##FIXME: Is there a reason to inherit this object ?
367
 
    _inherit = 'res.groups'
368
 
    _columns = {
369
 
        'users': fields.many2many('res.users', 'res_groups_users_rel', 'gid', 'uid', 'Users'),
370
 
    }
371
 
groups2()
372
 
 
373
 
class res_config_view(osv.osv_memory):
374
 
    _name = 'res.config.view'
375
 
    _inherit = 'res.config'
376
 
    _columns = {
377
 
        'name':fields.char('Name', size=64),
378
 
        'view': fields.selection([('simple','Simplified'),
379
 
                                  ('extended','Extended')],
380
 
                                 'Interface', required=True ),
381
 
    }
382
 
    _defaults={
383
 
        'view':lambda *args: 'simple',
384
 
    }
385
 
 
386
 
    def execute(self, cr, uid, ids, context=None):
387
 
        res=self.read(cr,uid,ids)[0]
388
 
        users_obj = self.pool.get('res.users')
389
 
        group_obj=self.pool.get('res.groups')
390
 
        if 'view' in res and res['view'] and res['view']=='extended':
391
 
            group_ids=group_obj.search(cr,uid,[('name','ilike','Extended')])
392
 
            if group_ids and len(group_ids):
393
 
                users_obj.write(cr, uid, [uid],{
394
 
                                'groups_id':[(4,group_ids[0])]
395
 
                            }, context=context)
396
 
res_config_view()
397
 
 
398
 
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
399