-
Notifications
You must be signed in to change notification settings - Fork 23.1k
/
res_users.py
2142 lines (1864 loc) · 92.8 KB
/
res_users.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import binascii
import contextlib
import datetime
import hmac
import ipaddress
import itertools
import json
import logging
import os
import time
from collections import defaultdict
from functools import wraps
from hashlib import sha256
from itertools import chain, repeat
from markupsafe import Markup
import babel.core
import pytz
from lxml import etree
from lxml.builder import E
from passlib.context import CryptContext
from psycopg2 import sql
from odoo import api, fields, models, tools, SUPERUSER_ID, _, Command
from odoo.addons.base.models.ir_model import MODULE_UNINSTALL_FLAG
from odoo.exceptions import AccessDenied, AccessError, UserError, ValidationError
from odoo.http import request, DEFAULT_LANG
from odoo.osv import expression
from odoo.service.db import check_super
from odoo.tools import is_html_empty, partition, collections, frozendict, lazy_property
_logger = logging.getLogger(__name__)
# Only users who can modify the user (incl. the user herself) see the real contents of these fields
USER_PRIVATE_FIELDS = []
MIN_ROUNDS = 600_000
concat = chain.from_iterable
#
# Functions for manipulating boolean and selection pseudo-fields
#
def name_boolean_group(id):
return 'in_group_' + str(id)
def name_selection_groups(ids):
return 'sel_groups_' + '_'.join(str(it) for it in sorted(ids))
def is_boolean_group(name):
return name.startswith('in_group_')
def is_selection_groups(name):
return name.startswith('sel_groups_')
def is_reified_group(name):
return is_boolean_group(name) or is_selection_groups(name)
def get_boolean_group(name):
return int(name[9:])
def get_selection_groups(name):
return [int(v) for v in name[11:].split('_')]
def parse_m2m(commands):
"return a list of ids corresponding to a many2many value"
ids = []
for command in commands:
if isinstance(command, (tuple, list)):
if command[0] in (Command.UPDATE, Command.LINK):
ids.append(command[1])
elif command[0] == Command.CLEAR:
ids = []
elif command[0] == Command.SET:
ids = list(command[2])
else:
ids.append(command)
return ids
def _jsonable(o):
try: json.dumps(o)
except TypeError: return False
else: return True
def check_identity(fn):
""" Wrapped method should be an *action method* (called from a button
type=object), and requires extra security to be executed. This decorator
checks if the identity (password) has been checked in the last 10mn, and
pops up an identity check wizard if not.
Prevents access outside of interactive contexts (aka with a request)
"""
@wraps(fn)
def wrapped(self):
if not request:
raise UserError(_("This method can only be accessed over HTTP"))
if request.session.get('identity-check-last', 0) > time.time() - 10 * 60:
# update identity-check-last like github?
return fn(self)
w = self.sudo().env['res.users.identitycheck'].create({
'request': json.dumps([
{ # strip non-jsonable keys (e.g. mapped to recordsets like binary_field_real_user)
k: v for k, v in self.env.context.items()
if _jsonable(v)
},
self._name,
self.ids,
fn.__name__
])
})
return {
'type': 'ir.actions.act_window',
'res_model': 'res.users.identitycheck',
'res_id': w.id,
'name': _("Security Control"),
'target': 'new',
'views': [(False, 'form')],
}
wrapped.__has_check_identity = True
return wrapped
#----------------------------------------------------------
# Basic res.groups and res.users
#----------------------------------------------------------
class Groups(models.Model):
_name = "res.groups"
_description = "Access Groups"
_rec_name = 'full_name'
_order = 'name'
_allow_sudo_commands = False
name = fields.Char(required=True, translate=True)
users = fields.Many2many('res.users', 'res_groups_users_rel', 'gid', 'uid')
model_access = fields.One2many('ir.model.access', 'group_id', string='Access Controls', copy=True)
rule_groups = fields.Many2many('ir.rule', 'rule_group_rel',
'group_id', 'rule_group_id', string='Rules', domain="[('global', '=', False)]")
menu_access = fields.Many2many('ir.ui.menu', 'ir_ui_menu_group_rel', 'gid', 'menu_id', string='Access Menu')
view_access = fields.Many2many('ir.ui.view', 'ir_ui_view_group_rel', 'group_id', 'view_id', string='Views')
comment = fields.Text(translate=True)
category_id = fields.Many2one('ir.module.category', string='Application', index=True)
color = fields.Integer(string='Color Index')
full_name = fields.Char(compute='_compute_full_name', string='Group Name', search='_search_full_name')
share = fields.Boolean(string='Share Group', help="Group created to set access rights for sharing data with some users.")
_sql_constraints = [
('name_uniq', 'unique (category_id, name)', 'The name of the group must be unique within an application!')
]
@api.constrains('users')
def _check_one_user_type(self):
self.users._check_one_user_type()
@api.ondelete(at_uninstall=False)
def _unlink_except_settings_group(self):
classified = self.env['res.config.settings']._get_classified_fields()
for _name, _groups, implied_group in classified['group']:
if implied_group.id in self.ids:
raise ValidationError(_('You cannot delete a group linked with a settings field.'))
@api.depends('category_id.name', 'name')
def _compute_full_name(self):
# Important: value must be stored in environment of group, not group1!
for group, group1 in zip(self, self.sudo()):
if group1.category_id:
group.full_name = '%s / %s' % (group1.category_id.name, group1.name)
else:
group.full_name = group1.name
def _search_full_name(self, operator, operand):
lst = True
if isinstance(operand, bool):
return [('name', operator, operand)]
if isinstance(operand, str):
lst = False
operand = [operand]
where = []
for group in operand:
values = [v for v in group.split('/') if v]
group_name = values.pop().strip()
category_name = values and '/'.join(values).strip() or group_name
group_domain = [('name', operator, lst and [group_name] or group_name)]
category_ids = self.env['ir.module.category'].sudo()._search(
[('name', operator, [category_name] if lst else category_name)])
category_domain = [('category_id', 'in', category_ids)]
if operator in expression.NEGATIVE_TERM_OPERATORS and not values:
category_domain = expression.OR([category_domain, [('category_id', '=', False)]])
if (operator in expression.NEGATIVE_TERM_OPERATORS) == (not values):
sub_where = expression.AND([group_domain, category_domain])
else:
sub_where = expression.OR([group_domain, category_domain])
if operator in expression.NEGATIVE_TERM_OPERATORS:
where = expression.AND([where, sub_where])
else:
where = expression.OR([where, sub_where])
return where
@api.model
def _search(self, args, offset=0, limit=None, order=None, count=False, access_rights_uid=None):
# add explicit ordering if search is sorted on full_name
if order and order.startswith('full_name'):
groups = super(Groups, self).search(args)
groups = groups.sorted('full_name', reverse=order.endswith('DESC'))
groups = groups[offset:offset+limit] if limit else groups[offset:]
return len(groups) if count else groups.ids
return super(Groups, self)._search(args, offset=offset, limit=limit, order=order, count=count, access_rights_uid=access_rights_uid)
def copy(self, default=None):
self.ensure_one()
chosen_name = default.get('name') if default else ''
default_name = chosen_name or _('%s (copy)', self.name)
default = dict(default or {}, name=default_name)
return super(Groups, self).copy(default)
def write(self, vals):
if 'name' in vals:
if vals['name'].startswith('-'):
raise UserError(_('The name of the group can not start with "-"'))
# invalidate caches before updating groups, since the recomputation of
# field 'share' depends on method has_group()
# DLE P139
if self.ids:
self.env['ir.model.access'].call_cache_clearing_methods()
return super(Groups, self).write(vals)
def _ensure_xml_id(self):
"""Return the groups external identifiers, creating the external identifier for groups missing one"""
result = self.get_external_id()
missings = {group_id: f'__custom__.group_{group_id}' for group_id, ext_id in result.items() if not ext_id}
if missings:
self.env['ir.model.data'].sudo().create(
[
{
'name': name.split('.')[1],
'model': 'res.groups',
'res_id': group_id,
'module': name.split('.')[0],
}
for group_id, name in missings.items()
]
)
result.update(missings)
return result
class ResUsersLog(models.Model):
_name = 'res.users.log'
_order = 'id desc'
_description = 'Users Log'
# Currenly only uses the magical fields: create_uid, create_date,
# for recording logins. To be extended for other uses (chat presence, etc.)
@api.autovacuum
def _gc_user_logs(self):
self._cr.execute("""
DELETE FROM res_users_log log1 WHERE EXISTS (
SELECT 1 FROM res_users_log log2
WHERE log1.create_uid = log2.create_uid
AND log1.create_date < log2.create_date
)
""")
_logger.info("GC'd %d user log entries", self._cr.rowcount)
class Users(models.Model):
""" User class. A res.users record models an OpenERP user and is different
from an employee.
res.users class now inherits from res.partner. The partner model is
used to store the data related to the partner: lang, name, address,
avatar, ... The user model is now dedicated to technical data.
"""
_name = "res.users"
_description = 'User'
_inherits = {'res.partner': 'partner_id'}
_order = 'name, login'
_allow_sudo_commands = False
@property
def SELF_READABLE_FIELDS(self):
""" The list of fields a user can read on their own user record.
In order to add fields, please override this property on model extensions.
"""
return [
'signature', 'company_id', 'login', 'email', 'name', 'image_1920',
'image_1024', 'image_512', 'image_256', 'image_128', 'lang', 'tz',
'tz_offset', 'groups_id', 'partner_id', '__last_update', 'action_id',
'avatar_1920', 'avatar_1024', 'avatar_512', 'avatar_256', 'avatar_128',
'share',
]
@property
def SELF_WRITEABLE_FIELDS(self):
""" The list of fields a user can write on their own user record.
In order to add fields, please override this property on model extensions.
"""
return ['signature', 'action_id', 'company_id', 'email', 'name', 'image_1920', 'lang', 'tz']
def _default_groups(self):
"""Default groups for employees
All the groups of the Template User
"""
default_user = self.env.ref('base.default_user', raise_if_not_found=False)
return default_user.sudo().groups_id if default_user else []
partner_id = fields.Many2one('res.partner', required=True, ondelete='restrict', auto_join=True, index=True,
string='Related Partner', help='Partner-related data of the user')
login = fields.Char(required=True, help="Used to log into the system")
password = fields.Char(
compute='_compute_password', inverse='_set_password',
invisible=True, copy=False,
help="Keep empty if you don't want the user to be able to connect on the system.")
new_password = fields.Char(string='Set Password',
compute='_compute_password', inverse='_set_new_password',
help="Specify a value only when creating a user or if you're "\
"changing the user's password, otherwise leave empty. After "\
"a change of password, the user has to login again.")
signature = fields.Html(string="Email Signature", compute='_compute_signature', readonly=False, store=True)
active = fields.Boolean(default=True)
active_partner = fields.Boolean(related='partner_id.active', readonly=True, string="Partner is Active")
action_id = fields.Many2one('ir.actions.actions', string='Home Action',
help="If specified, this action will be opened at log on for this user, in addition to the standard menu.")
groups_id = fields.Many2many('res.groups', 'res_groups_users_rel', 'uid', 'gid', string='Groups', default=lambda s: s._default_groups())
log_ids = fields.One2many('res.users.log', 'create_uid', string='User log entries')
login_date = fields.Datetime(related='log_ids.create_date', string='Latest authentication', readonly=False)
share = fields.Boolean(compute='_compute_share', compute_sudo=True, string='Share User', store=True,
help="External user with limited access, created only for the purpose of sharing data.")
companies_count = fields.Integer(compute='_compute_companies_count', string="Number of Companies")
tz_offset = fields.Char(compute='_compute_tz_offset', string='Timezone offset', invisible=True)
# Special behavior for this field: res.company.search() will only return the companies
# available to the current user (should be the user's companies?), when the user_preference
# context is set.
company_id = fields.Many2one('res.company', string='Company', required=True, default=lambda self: self.env.company.id,
help='The default company for this user.', context={'user_preference': True})
company_ids = fields.Many2many('res.company', 'res_company_users_rel', 'user_id', 'cid',
string='Companies', default=lambda self: self.env.company.ids)
# overridden inherited fields to bypass access rights, in case you have
# access to the user but not its corresponding partner
name = fields.Char(related='partner_id.name', inherited=True, readonly=False)
email = fields.Char(related='partner_id.email', inherited=True, readonly=False)
accesses_count = fields.Integer('# Access Rights', help='Number of access rights that apply to the current user',
compute='_compute_accesses_count', compute_sudo=True)
rules_count = fields.Integer('# Record Rules', help='Number of record rules that apply to the current user',
compute='_compute_accesses_count', compute_sudo=True)
groups_count = fields.Integer('# Groups', help='Number of groups that apply to the current user',
compute='_compute_accesses_count', compute_sudo=True)
_sql_constraints = [
('login_key', 'UNIQUE (login)', 'You can not have two users with the same login !')
]
def init(self):
cr = self.env.cr
# allow setting plaintext passwords via SQL and have them
# automatically encrypted at startup: look for passwords which don't
# match the "extended" MCF and pass those through passlib.
# Alternative: iterate on *all* passwords and use CryptContext.identify
cr.execute(r"""
SELECT id, password FROM res_users
WHERE password IS NOT NULL
AND password !~ '^\$[^$]+\$[^$]+\$.'
""")
if self.env.cr.rowcount:
Users = self.sudo()
for uid, pw in cr.fetchall():
Users.browse(uid).password = pw
def _set_password(self):
ctx = self._crypt_context()
for user in self:
self._set_encrypted_password(user.id, ctx.hash(user.password))
def _set_encrypted_password(self, uid, pw):
assert self._crypt_context().identify(pw) != 'plaintext'
self.env.cr.execute(
'UPDATE res_users SET password=%s WHERE id=%s',
(pw, uid)
)
self.browse(uid).invalidate_recordset(['password'])
def _check_credentials(self, password, env):
""" Validates the current user's password.
Override this method to plug additional authentication methods.
Overrides should:
* call `super` to delegate to parents for credentials-checking
* catch AccessDenied and perform their own checking
* (re)raise AccessDenied if the credentials are still invalid
according to their own validation method
When trying to check for credentials validity, call _check_credentials
instead.
"""
""" Override this method to plug additional authentication methods"""
assert password
self.env.cr.execute(
"SELECT COALESCE(password, '') FROM res_users WHERE id=%s",
[self.env.user.id]
)
[hashed] = self.env.cr.fetchone()
valid, replacement = self._crypt_context()\
.verify_and_update(password, hashed)
if replacement is not None:
self._set_encrypted_password(self.env.user.id, replacement)
if not valid:
raise AccessDenied()
def _compute_password(self):
for user in self:
user.password = ''
user.new_password = ''
def _set_new_password(self):
for user in self:
if not user.new_password:
# Do not update the password if no value is provided, ignore silently.
# For example web client submits False values for all empty fields.
continue
if user == self.env.user:
# To change their own password, users must use the client-specific change password wizard,
# so that the new password is immediately used for further RPC requests, otherwise the user
# will face unexpected 'Access Denied' exceptions.
raise UserError(_('Please use the change password wizard (in User Preferences or User menu) to change your own password.'))
else:
user.password = user.new_password
@api.depends('name')
def _compute_signature(self):
for user in self.filtered(lambda user: user.name and is_html_empty(user.signature)):
user.signature = Markup('<p>--<br />%s</p>') % user['name']
@api.depends('groups_id')
def _compute_share(self):
user_group_id = self.env['ir.model.data']._xmlid_to_res_id('base.group_user')
internal_users = self.filtered_domain([('groups_id', 'in', [user_group_id])])
internal_users.share = False
(self - internal_users).share = True
@api.depends('company_id')
def _compute_companies_count(self):
self.companies_count = self.env['res.company'].sudo().search_count([])
@api.depends('tz')
def _compute_tz_offset(self):
for user in self:
user.tz_offset = datetime.datetime.now(pytz.timezone(user.tz or 'GMT')).strftime('%z')
@api.depends('groups_id')
def _compute_accesses_count(self):
for user in self:
groups = user.groups_id
user.accesses_count = len(groups.model_access)
user.rules_count = len(groups.rule_groups)
user.groups_count = len(groups)
@api.onchange('login')
def on_change_login(self):
if self.login and tools.single_email_re.match(self.login):
self.email = self.login
@api.onchange('parent_id')
def onchange_parent_id(self):
return self.partner_id.onchange_parent_id()
def _read(self, fields):
super(Users, self)._read(fields)
if set(USER_PRIVATE_FIELDS).intersection(fields):
if self.check_access_rights('write', raise_exception=False):
return
for record in self:
for f in USER_PRIVATE_FIELDS:
try:
record._cache[f]
record._cache[f] = '********'
except Exception:
# skip SpecialValue (e.g. for missing record or access right)
pass
@api.constrains('company_id', 'company_ids', 'active')
def _check_company(self):
for user in self.filtered(lambda u: u.active):
if user.company_id not in user.company_ids:
raise ValidationError(
_('Company %(company_name)s is not in the allowed companies for user %(user_name)s (%(company_allowed)s).',
company_name=user.company_id.name,
user_name=user.name,
company_allowed=', '.join(user.mapped('company_ids.name')))
)
@api.constrains('action_id')
def _check_action_id(self):
action_open_website = self.env.ref('base.action_open_website', raise_if_not_found=False)
if action_open_website and any(user.action_id.id == action_open_website.id for user in self):
raise ValidationError(_('The "App Switcher" action cannot be selected as home action.'))
# Prevent using reload actions.
# We use sudo() because "Access rights" admins can't read action models
for user in self.sudo():
if user.action_id.type == "ir.actions.client":
action = self.env["ir.actions.client"].browse(user.action_id.id) # magic
if action.tag == "reload":
raise ValidationError(_('The "%s" action cannot be selected as home action.', action.name))
@api.constrains('groups_id')
def _check_one_user_type(self):
"""We check that no users are both portal and users (same with public).
This could typically happen because of implied groups.
"""
user_types_category = self.env.ref('base.module_category_user_type', raise_if_not_found=False)
user_types_groups = self.env['res.groups'].search(
[('category_id', '=', user_types_category.id)]) if user_types_category else False
if user_types_groups: # needed at install
if self._has_multiple_groups(user_types_groups.ids):
raise ValidationError(_('The user cannot have more than one user types.'))
def _has_multiple_groups(self, group_ids):
"""The method is not fast if the list of ids is very long;
so we rather check all users than limit to the size of the group
:param group_ids: list of group ids
:return: boolean: is there at least a user in at least 2 of the provided groups
"""
if group_ids:
args = [tuple(group_ids)]
if len(self.ids) == 1:
where_clause = "AND r.uid = %s"
args.append(self.id)
else:
where_clause = "" # default; we check ALL users (actually pretty efficient)
query = """
SELECT 1 FROM res_groups_users_rel WHERE EXISTS(
SELECT r.uid
FROM res_groups_users_rel r
WHERE r.gid IN %s""" + where_clause + """
GROUP BY r.uid HAVING COUNT(r.gid) > 1
)
"""
self.env.cr.execute(query, args)
return bool(self.env.cr.fetchall())
else:
return False
def toggle_active(self):
for user in self:
if not user.active and not user.partner_id.active:
user.partner_id.toggle_active()
super(Users, self).toggle_active()
def read(self, fields=None, load='_classic_read'):
if fields and self == self.env.user:
readable = self.SELF_READABLE_FIELDS
for key in fields:
if not (key in readable or key.startswith('context_')):
break
else:
# safe fields only, so we read as super-user to bypass access rights
self = self.sudo()
return super(Users, self).read(fields=fields, load=load)
@api.model
def read_group(self, domain, fields, groupby, offset=0, limit=None, orderby=False, lazy=True):
groupby_fields = set([groupby] if isinstance(groupby, str) else groupby)
if groupby_fields.intersection(USER_PRIVATE_FIELDS):
raise AccessError(_("Invalid 'group by' parameter"))
return super(Users, self).read_group(domain, fields, groupby, offset=offset, limit=limit, orderby=orderby, lazy=lazy)
@api.model
def _search(self, args, offset=0, limit=None, order=None, count=False, access_rights_uid=None):
if not self.env.su and args:
domain_fields = {term[0] for term in args if isinstance(term, (tuple, list))}
if domain_fields.intersection(USER_PRIVATE_FIELDS):
raise AccessError(_('Invalid search criterion'))
return super(Users, self)._search(args, offset=offset, limit=limit, order=order, count=count,
access_rights_uid=access_rights_uid)
@api.model_create_multi
def create(self, vals_list):
users = super(Users, self).create(vals_list)
for user in users:
# if partner is global we keep it that way
if user.partner_id.company_id:
user.partner_id.company_id = user.company_id
user.partner_id.active = user.active
return users
def _apply_groups_to_existing_employees(self):
""" Should new groups be added to existing employees?
If the template user is being modified, the groups should be applied to
every other base_user users
"""
default_user = self.env.ref('base.default_user', raise_if_not_found=False)
return default_user and default_user in self
def write(self, values):
if values.get('active') and SUPERUSER_ID in self._ids:
raise UserError(_("You cannot activate the superuser."))
if values.get('active') == False and self._uid in self._ids:
raise UserError(_("You cannot deactivate the user you're currently logged in as."))
if values.get('active'):
for user in self:
if not user.active and not user.partner_id.active:
user.partner_id.toggle_active()
if self == self.env.user:
writeable = self.SELF_WRITEABLE_FIELDS
for key in list(values):
if not (key in writeable or key.startswith('context_')):
break
else:
if 'company_id' in values:
if values['company_id'] not in self.env.user.company_ids.ids:
del values['company_id']
# safe fields only, so we write as super-user to bypass access rights
self = self.sudo().with_context(binary_field_real_user=self.env.user)
old_groups = []
if 'groups_id' in values and self._apply_groups_to_existing_employees():
# if modify groups_id content, compute the delta of groups to apply
# the new ones to other existing users
old_groups = self._default_groups()
res = super(Users, self).write(values)
if old_groups:
# new elements in _default_groups() means new groups for default users
# that needs to be added to existing ones as well for consistency
added_groups = self._default_groups() - old_groups
if added_groups:
internal_users = self.env.ref('base.group_user').users - self
internal_users.write({'groups_id': [Command.link(gid) for gid in added_groups.ids]})
if 'company_id' in values:
for user in self:
# if partner is global we keep it that way
if user.partner_id.company_id and user.partner_id.company_id.id != values['company_id']:
user.partner_id.write({'company_id': user.company_id.id})
if 'company_id' in values or 'company_ids' in values:
# Reset lazy properties `company` & `companies` on all envs
# This is unlikely in a business code to change the company of a user and then do business stuff
# but in case it happens this is handled.
# e.g. `account_test_savepoint.py` `setup_company_data`, triggered by `test_account_invoice_report.py`
for env in list(self.env.transaction.envs):
if env.user in self:
lazy_property.reset_all(env)
# clear caches linked to the users
if self.ids and 'groups_id' in values:
# DLE P139: Calling invalidate_cache on a new, well you lost everything as you wont be able to take it back from the cache
# `test_00_equipment_multicompany_user`
self.env['ir.model.access'].call_cache_clearing_methods()
# per-method / per-model caches have been removed so the various
# clear_cache/clear_caches methods pretty much just end up calling
# Registry._clear_cache
invalidation_fields = self._get_invalidation_fields()
if (invalidation_fields & values.keys()) or any(key.startswith('context_') for key in values):
self.clear_caches()
return res
@api.ondelete(at_uninstall=True)
def _unlink_except_master_data(self):
portal_user_template = self.env.ref('base.template_portal_user_id', False)
default_user_template = self.env.ref('base.default_user', False)
if SUPERUSER_ID in self.ids:
raise UserError(_('You can not remove the admin user as it is used internally for resources created by Odoo (updates, module installation, ...)'))
user_admin = self.env.ref('base.user_admin', raise_if_not_found=False)
if user_admin and user_admin in self:
raise UserError(_('You cannot delete the admin user because it is utilized in various places (such as security configurations,...). Instead, archive it.'))
self.clear_caches()
if (portal_user_template and portal_user_template in self) or (default_user_template and default_user_template in self):
raise UserError(_('Deleting the template users is not allowed. Deleting this profile will compromise critical functionalities.'))
@api.model
def _name_search(self, name, args=None, operator='ilike', limit=100, name_get_uid=None):
args = args or []
user_ids = []
if operator not in expression.NEGATIVE_TERM_OPERATORS:
if operator == 'ilike' and not (name or '').strip():
domain = []
else:
domain = [('login', '=', name)]
user_ids = self._search(expression.AND([domain, args]), limit=limit, access_rights_uid=name_get_uid)
if not user_ids:
user_ids = self._search(expression.AND([[('name', operator, name)], args]), limit=limit, access_rights_uid=name_get_uid)
return user_ids
def copy(self, default=None):
self.ensure_one()
default = dict(default or {})
if ('name' not in default) and ('partner_id' not in default):
default['name'] = _("%s (copy)", self.name)
if 'login' not in default:
default['login'] = _("%s (copy)", self.login)
return super(Users, self).copy(default)
@api.model
@tools.ormcache('self._uid')
def context_get(self):
user = self.env.user
# determine field names to read
name_to_key = {
name: name[8:] if name.startswith('context_') else name
for name in self._fields
if name.startswith('context_') or name in ('lang', 'tz')
}
# use read() to not read other fields: this must work while modifying
# the schema of models res.users or res.partner
values = user.read(list(name_to_key), load=False)[0]
context = {
key: values[name]
for name, key in name_to_key.items()
}
# ensure lang is set and available
# context > request > company > english > any lang installed
langs = [code for code, _ in self.env['res.lang'].get_installed()]
lang = context.get('lang')
if lang not in langs:
lang = request.best_lang if request else None
if lang not in langs:
lang = self.env.user.company_id.partner_id.lang
if lang not in langs:
lang = DEFAULT_LANG
if lang not in langs:
lang = langs[0] if langs else DEFAULT_LANG
context['lang'] = lang
# ensure uid is set
context['uid'] = self.env.uid
return frozendict(context)
@tools.ormcache('self.id')
def _get_company_ids(self):
# use search() instead of `self.company_ids` to avoid extra query for `active_test`
domain = [('active', '=', True), ('user_ids', 'in', self.id)]
return self.env['res.company'].search(domain)._ids
@api.model
def action_get(self):
return self.sudo().env.ref('base.action_res_users_my').read()[0]
def check_super(self, passwd):
return check_super(passwd)
@api.model
def _get_invalidation_fields(self):
return {
'groups_id', 'active', 'lang', 'tz', 'company_id', 'company_ids',
*USER_PRIVATE_FIELDS,
*self._get_session_token_fields()
}
@api.model
def _update_last_login(self):
# only create new records to avoid any side-effect on concurrent transactions
# extra records will be deleted by the periodical garbage collection
self.env['res.users.log'].create({}) # populated by defaults
@api.model
def _get_login_domain(self, login):
return [('login', '=', login)]
@api.model
def _get_email_domain(self, email):
return [('email', '=', email)]
@api.model
def _get_login_order(self):
return self._order
@classmethod
def _login(cls, db, login, password, user_agent_env):
if not password:
raise AccessDenied()
ip = request.httprequest.environ['REMOTE_ADDR'] if request else 'n/a'
try:
with cls.pool.cursor() as cr:
self = api.Environment(cr, SUPERUSER_ID, {})[cls._name]
with self._assert_can_auth(user=login):
user = self.search(self._get_login_domain(login), order=self._get_login_order(), limit=1)
if not user:
raise AccessDenied()
user = user.with_user(user)
user._check_credentials(password, user_agent_env)
tz = request.httprequest.cookies.get('tz') if request else None
if tz in pytz.all_timezones and (not user.tz or not user.login_date):
# first login or missing tz -> set tz to browser tz
user.tz = tz
user._update_last_login()
except AccessDenied:
_logger.info("Login failed for db:%s login:%s from %s", db, login, ip)
raise
_logger.info("Login successful for db:%s login:%s from %s", db, login, ip)
return user.id
@classmethod
def authenticate(cls, db, login, password, user_agent_env):
"""Verifies and returns the user ID corresponding to the given
``login`` and ``password`` combination, or False if there was
no matching user.
:param str db: the database on which user is trying to authenticate
:param str login: username
:param str password: user password
:param dict user_agent_env: environment dictionary describing any
relevant environment attributes
"""
uid = cls._login(db, login, password, user_agent_env=user_agent_env)
if user_agent_env and user_agent_env.get('base_location'):
with cls.pool.cursor() as cr:
env = api.Environment(cr, uid, {})
if env.user.has_group('base.group_system'):
# Successfully logged in as system user!
# Attempt to guess the web base url...
try:
base = user_agent_env['base_location']
ICP = env['ir.config_parameter']
if not ICP.get_param('web.base.url.freeze'):
ICP.set_param('web.base.url', base)
except Exception:
_logger.exception("Failed to update web.base.url configuration parameter")
return uid
@classmethod
@tools.ormcache('uid', 'passwd')
def check(cls, db, uid, passwd):
"""Verifies that the given (uid, password) is authorized for the database ``db`` and
raise an exception if it is not."""
if not passwd:
# empty passwords disallowed for obvious security reasons
raise AccessDenied()
with contextlib.closing(cls.pool.cursor()) as cr:
self = api.Environment(cr, uid, {})[cls._name]
with self._assert_can_auth(user=uid):
if not self.env.user.active:
raise AccessDenied()
self._check_credentials(passwd, {'interactive': False})
def _get_session_token_fields(self):
return {'id', 'login', 'password', 'active'}
@tools.ormcache('sid')
def _compute_session_token(self, sid):
""" Compute a session token given a session id and a user id """
# retrieve the fields used to generate the session token
session_fields = ', '.join(sorted(self._get_session_token_fields()))
self.env.cr.execute("""SELECT %s, (SELECT value FROM ir_config_parameter WHERE key='database.secret')
FROM res_users
WHERE id=%%s""" % (session_fields), (self.id,))
if self.env.cr.rowcount != 1:
self.clear_caches()
return False
data_fields = self.env.cr.fetchone()
# generate hmac key
key = (u'%s' % (data_fields,)).encode('utf-8')
# hmac the session id
data = sid.encode('utf-8')
h = hmac.new(key, data, sha256)
# keep in the cache the token
return h.hexdigest()
@api.model
def change_password(self, old_passwd, new_passwd):
"""Change current user password. Old password must be provided explicitly
to prevent hijacking an existing user session, or for cases where the cleartext
password is not used to authenticate requests.
:return: True
:raise: odoo.exceptions.AccessDenied when old password is wrong
:raise: odoo.exceptions.UserError when new password is not set or empty
"""
if not old_passwd:
raise AccessDenied()
# alternatively: use identitycheck wizard?
self._check_credentials(old_passwd, {'interactive': True})
# use self.env.user here, because it has uid=SUPERUSER_ID
self.env.user._change_password(new_passwd)
return True
def _change_password(self, new_passwd):
new_passwd = new_passwd.strip()
if not new_passwd:
raise UserError(_("Setting empty passwords is not allowed for security reasons!"))
ip = request.httprequest.environ['REMOTE_ADDR'] if request else 'n/a'
_logger.info(
"Password change for %r (#%d) by %r (#%d) from %s",
self.login, self.id,
self.env.user.login, self.env.user.id,
ip
)
self.password = new_passwd
def _deactivate_portal_user(self, **post):
"""Try to remove the current portal user.
This is used to give the opportunity to portal users to de-activate their accounts.
Indeed, as the portal users can easily create accounts, they will sometimes wish
it removed because they don't use this Odoo portal anymore.
Before this feature, they would have to contact the website or the support to get
their account removed, which could be tedious.
"""
non_portal_users = self.filtered(lambda user: not user.share)
if non_portal_users:
raise AccessDenied(_(
'Only the portal users can delete their accounts. '
'The user(s) %s can not be deleted.',
', '.join(non_portal_users.mapped('name')),
))
ip = request.httprequest.environ['REMOTE_ADDR'] if request else 'n/a'
res_users_deletion_values = []
for user in self:
_logger.info(
'Account deletion asked for "%s" (#%i) from %s. '
'Archive the user and remove login information.',
user.login, user.id, ip,
)
user.write({
'login': f'__deleted_user_{user.id}_{time.time()}',
'password': '',
})
user.api_key_ids._remove()
res_users_deletion_values.append({
'user_id': user.id,
'state': 'todo',
})
# Here we try to archive the user / partner, and then add the user in a deletion
# queue, to remove it from the database. As the deletion might fail (if the
# partner is related to an invoice e.g.) it's important to archive it here.
try:
# A user can not self-deactivate
self.with_user(SUPERUSER_ID).action_archive()
except Exception:
pass
try:
self.partner_id.action_archive()
except Exception:
pass
# Add users in the deletion queue
self.env['res.users.deletion'].create(res_users_deletion_values)
def preference_save(self):
return {
'type': 'ir.actions.client',
'tag': 'reload_context',
}
@check_identity
def preference_change_password(self):
return {
'type': 'ir.actions.act_window',
'target': 'new',
'res_model': 'change.password.own',
'view_mode': 'form',
}
@api.model
def has_group(self, group_ext_id):
# use singleton's id if called on a non-empty recordset, otherwise
# context uid
uid = self.id
if uid and uid != self._uid:
self = self.with_user(uid)
return self._has_group(group_ext_id)
@api.model
@tools.ormcache('self._uid', 'group_ext_id')
def _has_group(self, group_ext_id):
"""Checks whether user belongs to given group.
:param str group_ext_id: external ID (XML ID) of the group.