[REF] *: record.env.user._is_XXX() -> record.env.is_XXX()

Superuser mode implies `record.env.is_XXX()`.
This commit is contained in:
Raphael Collet
2019-07-04 11:32:22 +00:00
parent b7fd679a6c
commit 368e9530f4
25 changed files with 60 additions and 46 deletions
+2 -2
View File
@@ -11,7 +11,7 @@ class OnboardingController(http.Controller):
the permission to see it. """
company = request.env.company
if not request.env.user._is_admin() or \
if not request.env.is_admin() or \
company.account_invoice_onboarding_state == 'closed':
return {}
@@ -29,7 +29,7 @@ class OnboardingController(http.Controller):
the permission to see it. """
company = request.env.company
if not request.env.user._is_admin() or \
if not request.env.is_admin() or \
company.account_dashboard_onboarding_state == 'closed':
return {}
+2 -2
View File
@@ -1032,7 +1032,7 @@ class AccountMove(models.Model):
let the user manually change it.
"""
# Check user group.
system_user = self.env.user._is_system()
system_user = self.env.is_system()
if not system_user:
return
@@ -1065,7 +1065,7 @@ class AccountMove(models.Model):
def _inverse_invoice_sequence_number_next(self):
''' Set the number_next on the sequence related to the invoice/bill/refund'''
# Check user group.
if not self.env.user._is_admin():
if not self.env.is_admin():
return
# Set the next number in the sequence.
+1 -1
View File
@@ -192,7 +192,7 @@ class AccountChartTemplate(models.Model):
company = self.env.company
# Ensure everything is translated to the company's language, not the user's one.
self = self.with_context(lang=company.partner_id.lang)
if not self.env.user._is_admin():
if not self.env.is_admin():
raise AccessError(_("Only administrators can load a charf of accounts"))
existing_accounts = self.env['account.account'].search([('company_id', '=', company.id)])
+1 -1
View File
@@ -251,7 +251,7 @@ class GamificationBadge(models.Model):
:param badge_id: the granted badge id
:return: integer representing the permission.
"""
if self.env.user._is_admin():
if self.env.is_admin():
return self.CAN_GRANT
if self.rule_auth == 'nobody':
+1 -1
View File
@@ -52,7 +52,7 @@ class GoogleDrive(models.Model):
def get_access_token(self, scope=None):
Config = self.env['ir.config_parameter'].sudo()
google_drive_refresh_token = Config.get_param('google_drive_refresh_token')
user_is_admin = self.env['res.users'].browse(self.env.user.id)._is_admin()
user_is_admin = self.env.is_admin()
if not google_drive_refresh_token:
if user_is_admin:
dummy, action_id = self.env['ir.model.data'].get_object_reference('base_setup', 'action_general_configuration')
+2 -2
View File
@@ -6,7 +6,7 @@ from random import choice
from string import digits
from werkzeug import url_encode
from odoo import api, fields, models, tools, SUPERUSER_ID, _
from odoo import api, fields, models, tools, _
from odoo.exceptions import ValidationError, AccessError
from odoo.modules.module import get_module_resource
@@ -322,7 +322,7 @@ class HrEmployeePrivate(models.Model):
to post messages as the correct user.
"""
real_user = self.env.context.get('binary_field_real_user')
if self.env.user.id == SUPERUSER_ID and real_user:
if self.env.is_superuser() and real_user:
self = self.with_user(real_user)
return self
+2 -2
View File
@@ -9,7 +9,7 @@ import math
from datetime import datetime, time
from pytz import timezone, UTC
from odoo import api, fields, models, tools, SUPERUSER_ID
from odoo import api, fields, models, tools
from odoo.addons.resource.models.resource import float_to_time, HOURS_PER_DAY
from odoo.exceptions import AccessError, UserError, ValidationError
from odoo.tools import float_compare
@@ -823,7 +823,7 @@ class HolidaysRequest(models.Model):
def _check_approval_update(self, state):
""" Check if target state is achievable. """
if self.env.user.id == SUPERUSER_ID:
if self.env.is_superuser():
return
current_employee = self.env['hr.employee'].search([('user_id', '=', self.env.uid)], limit=1)
+1 -1
View File
@@ -337,7 +337,7 @@ class AccountMove(models.Model):
else:
_logger.info(_('Company not found. The company\'s user is set by default.'))
if not self.env.user._is_superuser():
if not self.env.is_superuser():
if self.env.company != company:
raise UserError(_("You can only import invoice concern your current company: %s") % self.env.company.display_name)
+1 -1
View File
@@ -242,7 +242,7 @@ class MailActivity(models.Model):
* unlink: access rule OR
(``mail_post_access`` or write) rights on related documents);
"""
if self.env.user._is_superuser():
if self.env.is_superuser():
return self
if not self.check_access_rights(operation, raise_exception=False):
return self.env[self._name]
+3 -3
View File
@@ -9,7 +9,7 @@ from operator import itemgetter
from email.utils import formataddr
from openerp.http import request
from odoo import _, api, fields, models, modules, SUPERUSER_ID, tools
from odoo import _, api, fields, models, modules, tools
from odoo.exceptions import UserError, AccessError
from odoo.osv import expression
from odoo.tools import groupby
@@ -637,7 +637,7 @@ class Message(models.Model):
- otherwise: remove the id
"""
# Rules do not apply to administrator
if self._uid == SUPERUSER_ID:
if self.env.is_superuser():
return super(Message, self)._search(
args, offset=offset, limit=limit, order=order,
count=count, access_rights_uid=access_rights_uid)
@@ -739,7 +739,7 @@ class Message(models.Model):
model_record_ids.setdefault(vals['model'], set()).add(vals['res_id'])
return model_record_ids
if self._uid == SUPERUSER_ID:
if self.env.is_superuser():
return
# Non employees see only messages with a subtype (aka, not internal logs)
if not self.env['res.users'].has_group('base.group_user'):
@@ -44,7 +44,7 @@ class PaymentWizard(models.TransientModel):
('company_id', '=', env.company.id)], limit=1)
def _get_default_payment_acquirer_onboarding_value(self, key):
if not self.env.user._is_admin():
if not self.env.is_admin():
raise UserError(_("Only administrators can access this data."))
if self._data_fetched:
+1 -1
View File
@@ -14,7 +14,7 @@ class OnboardingController(http.Controller):
the permission to see it. """
company = request.env.company
if not request.env.user._is_admin() or \
if not request.env.is_admin() or \
company.sale_quotation_onboarding_state == 'closed':
return {}
+2 -2
View File
@@ -1,7 +1,7 @@
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models, SUPERUSER_ID
from odoo import api, fields, models
from odoo.http import request
@@ -22,7 +22,7 @@ class UtmMixin(models.AbstractModel):
values = super(UtmMixin, self).default_get(fields)
# We ignore UTM for salemen, except some requests that could be done as superuser_id to bypass access rights.
if self.env.uid != SUPERUSER_ID and self.env.user.has_group('sales_team.group_sale_salesman'):
if not self.env.is_superuser() and self.env.user.has_group('sales_team.group_sale_salesman'):
return values
for url_param, field_name, cookie_name in self.env['utm.mixin'].tracking_fields():
+5 -5
View File
@@ -255,7 +255,7 @@ class Post(models.Model):
user = self.env.user
# Won't impact sitemap, search() in converter is forced as public user
if user._is_admin():
if self.env.is_admin():
return [(1, '=', 1)]
req = """
@@ -344,7 +344,7 @@ class Post(models.Model):
@api.multi
def _get_post_karma_rights(self):
user = self.env.user
is_admin = user._is_admin()
is_admin = self.env.is_admin()
# sudoed recordset instead of individual posts so values can be
# prefetched in bulk
for post, post_sudo in zip(self, self.sudo()):
@@ -867,7 +867,7 @@ class Vote(models.Model):
@api.model
def create(self, vals):
# can't modify owner of a vote
if not self.env.user._is_admin():
if not self.env.is_admin():
vals.pop('user_id', None)
vote = super(Vote, self).create(vals)
@@ -882,7 +882,7 @@ class Vote(models.Model):
@api.multi
def write(self, values):
# can't modify owner of a vote
if not self.env.user._is_admin():
if not self.env.is_admin():
values.pop('user_id', None)
for vote in self:
@@ -904,7 +904,7 @@ class Vote(models.Model):
post = self.post_id
if vals.get('post_id'):
post = self.env['forum.post'].browse(vals.get('post_id'))
if not self.env.user._is_admin():
if not self.env.is_admin():
# own post check
if self._uid == post.create_uid.id:
raise UserError(_('It is not allowed to vote for its own post.'))
@@ -259,7 +259,7 @@ class Channel(models.Model):
for record in self:
if not record.can_upload:
record.can_publish = False
elif record.user_id == self.env.user or self.env.user._is_superuser():
elif record.user_id == self.env.user or self.env.is_superuser():
record.can_publish = True
else:
record.can_publish = self.env.user.has_group('website.group_website_publisher')
@@ -314,7 +314,7 @@ class Channel(models.Model):
@api.model
def create(self, vals):
# Ensure creator is member of its channel it is easier for him to manage it (unless it is odoobot)
if not vals.get('channel_partner_ids') and not self.env.user._is_superuser():
if not vals.get('channel_partner_ids') and not self.env.is_superuser():
vals['channel_partner_ids'] = [(0, 0, {
'partner_id': self.env.user.partner_id.id
})]
+1 -1
View File
@@ -760,7 +760,7 @@ class IrActionsReport(models.Model):
:param report_name: Name of the template to generate an action for
"""
discard_logo_check = self.env.context.get('discard_logo_check')
if (self.env.user._is_admin()) and ((not self.env.company.external_report_layout_id) or (not discard_logo_check and not self.env.company.logo)) and config:
if self.env.is_admin() and ((not self.env.company.external_report_layout_id) or (not discard_logo_check and not self.env.company.logo)) and config:
template = self.env.ref('base.view_company_report_form_with_print') if self.env.context.get('from_transient_model', False) else self.env.ref('base.view_company_report_form')
return {
'name': _('Choose Your Document Layout'),
+8 -8
View File
@@ -10,7 +10,7 @@ import re
from collections import defaultdict
import uuid
from odoo import api, fields, models, tools, SUPERUSER_ID, _
from odoo import api, fields, models, tools, _
from odoo.exceptions import AccessError, ValidationError, MissingError
from odoo.tools import config, human_size, ustr, html_escape
from odoo.tools.mimetypes import guess_mimetype
@@ -54,7 +54,7 @@ class IrAttachment(models.Model):
@api.model
def force_storage(self):
"""Force all attachments to be stored in the currently configured storage"""
if not self.env.user._is_admin():
if not self.env.is_admin():
raise AccessError(_('Only administrators can execute this action.'))
# domain to retrieve the attachments to migrate
@@ -314,7 +314,7 @@ class IrAttachment(models.Model):
# ir.http's dispatch exception handling
# XDO note: this should be done in check(write), constraints for access rights?
# XDO note: if read on sudo, read twice, one for constraints, one for _inverse_datas as user
if self.env.user._is_admin():
if self.env.is_admin():
return
if self.type == 'binary' and self.url:
has_group = self.env.user.has_group
@@ -327,7 +327,7 @@ class IrAttachment(models.Model):
In the 'document' module, it is overriden to relax this hard rule, since
more complex ones apply there.
"""
if self.env.user._is_superuser():
if self.env.is_superuser():
return True
# collect the records to check (by model)
model_ids = defaultdict(set) # {model_name: set(ids)}
@@ -335,7 +335,7 @@ class IrAttachment(models.Model):
if self:
self._cr.execute('SELECT res_model, res_id, create_uid, public, res_field FROM ir_attachment WHERE id IN %s', [tuple(self.ids)])
for res_model, res_id, create_uid, public, res_field in self._cr.fetchall():
if not self.env.user._is_system() and res_field:
if not self.env.is_system() and res_field:
raise AccessError(_("Sorry, you are not allowed to access this document."))
if public and mode == 'read':
continue
@@ -369,7 +369,7 @@ class IrAttachment(models.Model):
records.check_access_rule(mode)
if require_employee:
if not (self.env.user._is_admin() or self.env.user.has_group('base.group_user')):
if not (self.env.is_admin() or self.env.user.has_group('base.group_user')):
raise AccessError(_("Sorry, you are not allowed to access this document."))
def _read_group_allowed_fields(self):
@@ -387,7 +387,7 @@ class IrAttachment(models.Model):
groupby = [groupby] if isinstance(groupby, str) else groupby
allowed_fields = self._read_group_allowed_fields()
fields_set = set(field.split(':')[0] for field in fields + groupby)
if not self.env.user._is_system() and (not fields or fields_set.difference(allowed_fields)):
if not self.env.is_system() and (not fields or fields_set.difference(allowed_fields)):
raise AccessError(_("Sorry, you are not allowed to access these fields on attachments."))
return super().read_group(domain, fields, groupby, offset=offset, limit=limit, orderby=orderby, lazy=lazy)
@@ -401,7 +401,7 @@ class IrAttachment(models.Model):
ids = super(IrAttachment, self)._search(args, offset=offset, limit=limit, order=order,
count=False, access_rights_uid=access_rights_uid)
if self.env.user._is_system():
if self.env.is_system():
# rules do not apply for the superuser
return len(ids) if count else ids
+1 -1
View File
@@ -38,7 +38,7 @@ class AutoVacuum(models.AbstractModel):
@api.model
def power_on(self, *args, **kwargs):
if not self.env.user._is_admin():
if not self.env.is_admin():
raise AccessDenied()
self.env['ir.attachment']._file_gc()
self._gc_transient_models()
+3 -3
View File
@@ -988,7 +988,7 @@ class IrModelConstraint(models.Model):
"""
Delete PostgreSQL foreign keys and constraints tracked by this model.
"""
if not (self.env.su or self.env.user.has_group('base.group_system')):
if not self.env.is_system():
raise AccessError(_('Administrator access is required to uninstall a module'))
ids_set = set(self.ids)
@@ -1101,7 +1101,7 @@ class IrModelRelation(models.Model):
"""
Delete PostgreSQL many2many relations tracked by this model.
"""
if not (self.env.su or self.env.user.has_group('base.group_system')):
if not self.env.is_system():
raise AccessError(_('Administrator access is required to uninstall a module'))
ids_set = set(self.ids)
@@ -1566,7 +1566,7 @@ class IrModelData(models.Model):
the chance of gracefully deleting all records.
This step is performed as part of the full uninstallation of a module.
"""
if not (self.env.su or self.env.user.has_group('base.group_system')):
if not self.env.is_system():
raise AccessError(_('Administrator access is required to uninstall a module'))
# enable model/field deletion
+1 -1
View File
@@ -64,7 +64,7 @@ def assert_log_admin_access(method):
user = self.env.user
origin = request.httprequest.remote_addr if request else 'n/a'
log_data = (method.__name__, self.sudo().mapped('name'), user.login, user.id, origin)
if not self.env.user._is_admin():
if not self.env.is_admin():
_logger.warning('DENY access to module.%s on %s to user %s ID #%s via %s', *log_data)
raise AccessDenied()
_logger.info('ALLOW access to module.%s on %s to user %s #%s via %s', *log_data)
+1 -1
View File
@@ -514,7 +514,7 @@ class IrTranslation(models.Model):
""" Check access rights of operation ``mode`` on ``self`` for the
current user. Raise an AccessError in case conditions are not met.
"""
if self.env.user._is_superuser():
if self.env.is_superuser():
return
# collect translated field records (model_ids) and other translations
+1 -1
View File
@@ -612,7 +612,7 @@ class ResConfigSettings(models.TransientModel, ResConfigModuleInstallationMixin)
@api.multi
def execute(self):
self.ensure_one()
if not self.env.user._is_admin() and not self.env.user.has_group('base.group_system'):
if not self.env.is_admin():
raise AccessError(_("Only administrators can change the settings"))
self = self.with_context(active_test=False)
@@ -267,7 +267,7 @@ class MergePartnerAutomatic(models.TransientModel):
:param extra_checks: pass False to bypass extra sanity check (e.g. email address)
"""
# super-admin can be used to bypass extra checks
if self.env.user._is_admin():
if self.env.is_admin():
extra_checks = False
Partner = self.env['res.partner']
+14
View File
@@ -855,6 +855,20 @@ class Environment(Mapping):
""" return the record corresponding to the given ``xml_id`` """
return self['ir.model.data'].xmlid_to_object(xml_id, raise_if_not_found=raise_if_not_found)
def is_superuser(self):
""" Return whether the environment is in superuser mode. """
return self.su
def is_admin(self):
""" Return whether the current user has group "Access Rights", or is in
superuser mode. """
return self.su or self.user._is_admin()
def is_system(self):
""" Return whether the current user has group "Settings", or is in
superuser mode. """
return self.su or self.user._is_system()
@property
def user(self):
""" return the current user (as an instance) """
+2 -2
View File
@@ -1124,7 +1124,7 @@ class Field(MetaField('DummyField', (object,), {})):
def determine_draft_value(self, record):
""" Determine the value of ``self`` for the given draft ``record``. """
if self.compute:
if self.compute_sudo and record.env.uid != SUPERUSER_ID:
if self.compute_sudo and not record.env.su:
record_sudo = record.sudo()
copy_cache(record, record_sudo.env)
self.compute_value(record_sudo)
@@ -1824,7 +1824,7 @@ class Binary(Field):
decoded_value = base64.b64decode(value)
# Full mimetype detection
if (guess_mimetype(decoded_value).startswith('image/svg') and
not record.env.user._is_system()):
not record.env.is_system()):
raise UserError(_("Only admins can upload SVG files."))
if isinstance(value, bytes):
return psycopg2.Binary(value)