diff --git a/auditlog/__manifest__.py b/auditlog/__manifest__.py index 0bf459cbf71..4626a18a678 100644 --- a/auditlog/__manifest__.py +++ b/auditlog/__manifest__.py @@ -3,7 +3,7 @@ { 'name': "Audit Log", - 'version': "11.0.1.0.1", + 'version': "11.0.1.1.1", 'author': "ABF OSIELL,Odoo Community Association (OCA)", 'license': "AGPL-3", 'website': "https://github.com/OCA/server-tools/", diff --git a/auditlog/migrations/11.0.1.1.1/pre-migration.py b/auditlog/migrations/11.0.1.1.1/pre-migration.py new file mode 100644 index 00000000000..53a120e98bc --- /dev/null +++ b/auditlog/migrations/11.0.1.1.1/pre-migration.py @@ -0,0 +1,73 @@ +# © 2018 Pieter Paulussen +# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). +import logging + + +def migrate(cr, version): + if not version: + return + logger = logging.getLogger(__name__) + logger.info( + "Creating columns: auditlog_log (model_name, model_model) " + "and auditlog_log_line (field_name, field_description)." + ) + cr.execute( + """ + ALTER TABLE auditlog_log + ADD COLUMN IF NOT EXISTS model_name VARCHAR, + ADD COLUMN IF NOT EXISTS model_model VARCHAR; + ALTER TABLE auditlog_log_line + ADD COLUMN IF NOT EXISTS field_name VARCHAR, + ADD COLUMN IF NOT EXISTS field_description VARCHAR; + ALTER TABLE auditlog_rule + ADD COLUMN IF NOT EXISTS model_name VARCHAR, + ADD COLUMN IF NOT EXISTS model_model VARCHAR; + """ + ) + logger.info( + "Creating indexes on auditlog_log column 'model_id' and " + "auditlog_log_line column 'field_id'." + ) + cr.execute( + """ + CREATE INDEX IF NOT EXISTS + auditlog_log_model_id_index ON auditlog_log (model_id); + CREATE INDEX IF NOT EXISTS + auditlog_log_line_field_id_index ON auditlog_log_line (field_id); + """ + ) + logger.info( + "Preemptive fill auditlog_log columns: 'model_name' and " "'model_model'." + ) + cr.execute( + """ + UPDATE auditlog_log al + SET model_name = im.name, model_model = im.model + FROM ir_model im + WHERE im.id = al.model_id AND model_name IS NULL + """ + ) + logger.info( + "Preemtive fill of auditlog_log_line columns: 'field_name' and" + " 'field_description'." + ) + cr.execute( + """ + UPDATE auditlog_log_line al + SET field_name = imf.name, field_description = imf.field_description + FROM ir_model_fields imf + WHERE imf.id = al.field_id AND field_name IS NULL + """ + ) + logger.info( + "Preemptive fill auditlog_rule columns: 'model_name' and " "'model_model'." + ) + cr.execute( + """ + UPDATE auditlog_rule al + SET model_name = im.name, model_model = im.model + FROM ir_model im + WHERE im.id = al.model_id AND model_name IS NULL + """ + ) + logger.info("Successfully updated auditlog tables") diff --git a/auditlog/models/log.py b/auditlog/models/log.py index bbab1fc9211..fcc0bbc0f72 100644 --- a/auditlog/models/log.py +++ b/auditlog/models/log.py @@ -1,6 +1,7 @@ # Copyright 2015 ABF OSIELL # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). -from odoo import models, fields +from odoo import _, api, fields, models +from odoo.exceptions import UserError class AuditlogLog(models.Model): @@ -10,7 +11,13 @@ class AuditlogLog(models.Model): name = fields.Char("Resource Name", size=64) model_id = fields.Many2one( - 'ir.model', string="Model") + "ir.model", string="Model", index=True, + required=True + ) + model_name = fields.Char(readonly=True, related='model_id.name' ) + model_model = fields.Char(string="Technical Model Name", readonly=True, + related="model_id.model" + ) res_id = fields.Integer("Resource ID") user_id = fields.Many2one( 'res.users', string="User") @@ -33,7 +40,9 @@ class AuditlogLogLine(models.Model): _description = "Auditlog - Log details (fields updated)" field_id = fields.Many2one( - 'ir.model.fields', ondelete='cascade', string="Field", required=True) + "ir.model.fields", ondelete="set null", string="Field", index=True, + required=True + ) log_id = fields.Many2one( 'auditlog.log', string="Log", ondelete='cascade', index=True) old_value = fields.Text("Old Value") diff --git a/auditlog/models/rule.py b/auditlog/models/rule.py index 6cdc7233ccd..0ba9784fcbe 100644 --- a/auditlog/models/rule.py +++ b/auditlog/models/rule.py @@ -1,7 +1,10 @@ # Copyright 2015 ABF OSIELL # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). -from odoo import models, fields, api, modules, _ +import copy + +from odoo import _, api, fields, models, modules +from odoo.exceptions import UserError FIELDS_BLACKLIST = [ 'id', 'create_uid', 'create_date', 'write_uid', 'write_date', @@ -46,8 +49,15 @@ class AuditlogRule(models.Model): name = fields.Char("Name", size=32, required=True) model_id = fields.Many2one( - 'ir.model', "Model", required=True, - help="Select model for which you want to generate log.") + "ir.model", + "Model", + help="Select model for which you want to generate log.", + states={"subscribed": [("readonly", True)]}, + ondelete="set null", + index=True, + ) + model_name = fields.Char(readonly=True) + model_model = fields.Char(string="Technical Model Name", readonly=True) user_ids = fields.Many2many( 'res.users', 'audittail_rules_users', @@ -119,11 +129,11 @@ def _patch_methods(self): for rule in self: if rule.state != 'subscribed': continue - if not self.pool.get(rule.model_id.model): + if not self.pool.get(rule.model_id.model or rule.model_model): # ignore rules for models not loadable currently continue model_cache[rule.model_id.model] = rule.model_id.id - model_model = self.env[rule.model_id.model] + model_model = self.env[rule.model_id.model or rule.model_model] # CRUD # -> create check_attr = 'auditlog_ruled_create' @@ -160,10 +170,11 @@ def _revert_methods(self): """Restore original ORM methods of models defined in rules.""" updated = False for rule in self: - model_model = self.env[rule.model_id.model] - for method in ['create', 'read', 'write', 'unlink']: - if getattr(rule, 'log_%s' % method) and hasattr( - getattr(model_model, method), 'origin'): + model_model = self.env[rule.model_id.model or rule.model_model] + for method in ["create", "read", "write", "unlink"]: + if getattr(rule, "log_%s" % method) and hasattr( + getattr(model_model, method), "origin" + ): model_model._revert_method(method) delattr(type(model_model), 'auditlog_ruled_%s' % method) updated = True @@ -173,7 +184,11 @@ def _revert_methods(self): @api.model def create(self, vals): """Update the registry when a new rule is created.""" - new_record = super(AuditlogRule, self).create(vals) + if "model_id" not in vals or not vals["model_id"]: + raise UserError(_("No model defined to create line.")) + model = self.env["ir.model"].browse(vals["model_id"]) + vals.update({"model_name": model.name, "model_model": model.model}) + new_record = super().create(vals) if new_record._register_hook(): modules.registry.Registry(self.env.cr.dbname).signal_changes() return new_record @@ -181,10 +196,15 @@ def create(self, vals): @api.multi def write(self, vals): """Update the registry when existing rules are updated.""" - super(AuditlogRule, self).write(vals) + if "model_id" in vals: + if not vals["model_id"]: + raise UserError(_("Field 'model_id' cannot be empty.")) + model = self.env["ir.model"].browse(vals["model_id"]) + vals.update({"model_name": model.name, "model_model": model.model}) + res = super().write(vals) if self._register_hook(): modules.registry.Registry(self.env.cr.dbname).signal_changes() - return True + return res @api.multi def unlink(self): diff --git a/auditlog/readme/CONTRIBUTORS.rst b/auditlog/readme/CONTRIBUTORS.rst index 1567f0b2cdc..5b88f88de33 100644 --- a/auditlog/readme/CONTRIBUTORS.rst +++ b/auditlog/readme/CONTRIBUTORS.rst @@ -1,3 +1,7 @@ * Sebastien Alix * Holger Brunn * Holden Rehg +* Eric Lembregts +* Pieter Paulussen +* Alan Ramos +* Stefan Rijnhart diff --git a/auditlog/tests/test_auditlog.py b/auditlog/tests/test_auditlog.py index 996cf5fa12a..195a91e95cc 100644 --- a/auditlog/tests/test_auditlog.py +++ b/auditlog/tests/test_auditlog.py @@ -1,6 +1,11 @@ # Copyright 2015 Therp BV +# © 2018 Pieter Paulussen +# © 2021 Stefan Rijnhart # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). -from odoo.tests.common import TransactionCase +from odoo.modules.migration import load_script +from odoo.tests.common import SavepointCase, TransactionCase + +from odoo.addons.base.models.ir_model import MODULE_UNINSTALL_FLAG class AuditlogCommon(object): @@ -119,3 +124,114 @@ def setUp(self): def tearDown(self): self.groups_rule.unlink() super(TestAuditlogFast, self).tearDown() + + +class TestFieldRemoval(SavepointCase): + @classmethod + def setUpClass(cls): + super().setUpClass() + + # Clear all existing logging lines + existing_audit_logs = cls.env["auditlog.log"].search([]) + existing_audit_logs.unlink() + + # Create a test model to remove + cls.test_model = cls.env["ir.model"].create( + {"name": "x_test_model", "model": "x_test.model", "state": "manual"} + ) + + # Create a test model field to remove + cls.test_field = cls.env["ir.model.fields"].create( + { + "name": "x_test_field", + "field_description": "x_Test Field", + "model_id": cls.test_model.id, + "ttype": "char", + "state": "manual", + } + ) + + # Setup auditlog rule + cls.auditlog_rule = cls.env["auditlog.rule"].create( + { + "name": "test.model", + "model_id": cls.test_model.id, + "log_type": "fast", + "log_read": False, + "log_create": True, + "log_write": True, + "log_unlink": False, + } + ) + + cls.auditlog_rule.subscribe() + # Trigger log creation + rec = cls.env["x_test.model"].create({"x_test_field": "test value"}) + rec.write({"x_test_field": "test value 2"}) + + cls.logs = cls.env["auditlog.log"].search( + [("res_id", "=", rec.id), ("model_id", "=", cls.test_model.id)] + ) + + def assert_values(self): + """Assert that the denormalized field and model info is present + on the auditlog records""" + self.logs.refresh() + self.assertEqual(self.logs[0].model_name, "x_test_model") + self.assertEqual(self.logs[0].model_model, "x_test.model") + + log_lines = self.logs.mapped("line_ids") + self.assertEqual(len(log_lines), 2) + self.assertEqual(log_lines[0].field_name, "x_test_field") + self.assertEqual(log_lines[0].field_description, "x_Test Field") + + self.auditlog_rule.refresh() + self.assertEqual(self.auditlog_rule.model_name, "x_test_model") + self.assertEqual(self.auditlog_rule.model_model, "x_test.model") + + def test_01_field_and_model_removal(self): + """ Test field and model removal to check auditlog line persistence """ + self.assert_values() + + # Remove the field + self.test_field.with_context({MODULE_UNINSTALL_FLAG: True}).unlink() + self.assert_values() + # The field should not be linked + self.assertFalse(self.logs.mapped("line_ids.field_id")) + + # Remove the model + self.test_model.with_context({MODULE_UNINSTALL_FLAG: True}).unlink() + self.assert_values() + + # The model should not be linked + self.assertFalse(self.logs.mapped("model_id")) + # Assert rule values + self.assertFalse(self.auditlog_rule.model_id) + + def test_02_migration(self): + """Test the migration of the data model related to this feature""" + # Drop the data model + self.env.cr.execute( + """ALTER TABLE auditlog_log + DROP COLUMN model_name, DROP COLUMN model_model""" + ) + self.env.cr.execute( + """ALTER TABLE auditlog_rule + DROP COLUMN model_name, DROP COLUMN model_model""" + ) + self.env.cr.execute( + """ALTER TABLE auditlog_log_line + DROP COLUMN field_name, DROP COLUMN field_description""" + ) + + # Recreate the data model + mod = load_script( + "auditlog/migrations/14.0.1.1.0/pre-migration.py", "pre-migration" + ) + mod.migrate(self.env.cr, "14.0.1.0.2") + + # Values are restored + self.assert_values() + + # The migration script is tolerant if the data model is already in place + mod.migrate(self.env.cr, "14.0.1.0.2") diff --git a/auditlog/views/auditlog_view.xml b/auditlog/views/auditlog_view.xml index 2ec7b480896..f9d1e6a7020 100644 --- a/auditlog/views/auditlog_view.xml +++ b/auditlog/views/auditlog_view.xml @@ -104,9 +104,19 @@ - - - + + + + + @@ -117,7 +127,12 @@
- + + diff --git a/auditlog_security/README.rst b/auditlog_security/README.rst new file mode 100644 index 00000000000..438dfbd137a --- /dev/null +++ b/auditlog_security/README.rst @@ -0,0 +1,95 @@ +========================== +Audit Log User Permissions +========================== + +.. !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + !! This file is generated by oca-gen-addon-readme !! + !! changes will be overwritten. !! + !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + +.. |badge1| image:: https://img.shields.io/badge/maturity-Beta-yellow.png + :target: https://odoo-community.org/page/development-status + :alt: Beta +.. |badge2| image:: https://img.shields.io/badge/licence-AGPL--3-blue.png + :target: http://www.gnu.org/licenses/agpl-3.0-standalone.html + :alt: License: AGPL-3 +.. |badge3| image:: https://img.shields.io/badge/github-OCA%2Fserver--tools-lightgray.png?logo=github + :target: https://github.com/OCA/server-tools/tree/11.0/auditlog_security + :alt: OCA/server-tools +.. |badge4| image:: https://img.shields.io/badge/weblate-Translate%20me-F47D42.png + :target: https://translation.odoo-community.org/projects/server-tools-11-0/server-tools-11-0-auditlog_security + :alt: Translate me on Weblate +.. |badge5| image:: https://img.shields.io/badge/runbot-Try%20me-875A7B.png + :target: https://runbot.odoo-community.org/runbot/149/11.0 + :alt: Try me on Runbot + +|badge1| |badge2| |badge3| |badge4| |badge5| + +This module allows extends auditlog, allowing specific log lines to be viewed only +by users belonging to specific views, while all other lines are allowed only to +administrator. + +**Table of contents** + +.. contents:: + :local: + +Usage +===== + +Go to `Settings / Technical / Audit / Rules` to subscribe rules. A rule defines +which operations to log for a given data model. +The rule is now extended with a new field permission_ids, that tells us wich groups will +be allowed to read the lines produced by this rule. +If permission_ids is left empty, the default will be: +"auditlog lines visible only by user in Settings group, which is the default +for the auditlog module" + + +Then, check logs in the `Settings / Technical / Audit / Logs` menu. You can +group them by user sessions, date, data model , HTTP requests. + +Known issues / Roadmap +====================== + + + +Bug Tracker +=========== + +Bugs are tracked on `GitHub Issues `_. +In case of trouble, please check there if your issue has already been reported. +If you spotted it first, help us smashing it by providing a detailed and welcomed +`feedback `_. + +Do not contact contributors directly about support or help with technical issues. + +Credits +======= + +Authors +~~~~~~~ + +* Therp B.V. + +Contributors +~~~~~~~~~~~~ + +* Giovanni Francesco Capalbo + +Maintainers +~~~~~~~~~~~ + +This module is maintained by the OCA. + +.. image:: https://odoo-community.org/logo.png + :alt: Odoo Community Association + :target: https://odoo-community.org + +OCA, or the Odoo Community Association, is a nonprofit organization whose +mission is to support the collaborative development of Odoo features and +promote its widespread use. + +This module is part of the `OCA/server-tools `_ project on GitHub. + +You are welcome to contribute. To learn how please visit https://odoo-community.org/page/Contribute. diff --git a/auditlog_security/__init__.py b/auditlog_security/__init__.py new file mode 100644 index 00000000000..31660d6a965 --- /dev/null +++ b/auditlog_security/__init__.py @@ -0,0 +1,3 @@ +# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). + +from . import models diff --git a/auditlog_security/__manifest__.py b/auditlog_security/__manifest__.py new file mode 100644 index 00000000000..22218b90eec --- /dev/null +++ b/auditlog_security/__manifest__.py @@ -0,0 +1,25 @@ +# Copyright 2021 Therp B.V. +# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). + +{ + "name": "Audit Log User Permissions", + "version": "11.0.1.1.4", + "author": "Therp B.V.,Odoo Community Association (OCA)", + "license": "AGPL-3", + "website": "https://github.com/OCA/server-tools/", + "category": "Tools", + "description": """Allow regular users to view Audit log lines + via the form view of the relevant model""", + "depends": [ + "auditlog", + "contacts", + ], + "data": [ + "security/res_groups.xml", + "views/auditlog_view.xml", + "security/ir.model.access.csv", + "security/ir_rule.xml", + ], + "application": True, + "installable": True, +} diff --git a/auditlog_security/migrations/11.0.1.1.4/pre-migration.py b/auditlog_security/migrations/11.0.1.1.4/pre-migration.py new file mode 100644 index 00000000000..9083cb4b6fc --- /dev/null +++ b/auditlog_security/migrations/11.0.1.1.4/pre-migration.py @@ -0,0 +1,61 @@ +# © 2018 Pieter Paulussen +# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). +import logging + + +def migrate(cr, version): + if not version: + return + logger = logging.getLogger(__name__) + logger.info( + "Creating columns: auditlog_log_line (method. user_id) " + ) + cr.execute( + """ + ALTER TABLE auditlog_log_line + ADD COLUMN IF NOT EXISTS method VARCHAR, + ADD COLUMN IF NOT EXISTS user_id INTEGER, + ADD COLUMN IF NOT EXISTS model_id INTEGER, + ADD COLUMN IF NOT EXISTS res_id INTEGER; + + """ + ) + cr.execute( + """ + ALTER TABLE auditlog_log_line DROP CONSTRAINT IF EXISTS auditlog_log_line_user_id_fkey; + ALTER TABLE auditlog_log_line ADD constraint + auditlog_log_line_user_id_fkey + FOREIGN KEY (user_id) REFERENCES res_users(id) ON DELETE SET NULL; + ALTER TABLE auditlog_log_line DROP CONSTRAINT IF EXISTS auditlog_log_line_model_id_fkey; + ALTER TABLE auditlog_log_line ADD constraint + auditlog_log_line_model_id_fkey + FOREIGN KEY (model_id) REFERENCES ir_model(id) ON DELETE SET NULL; + """ + ) + logger.info( + "Creating indexes on auditlog_log_line column 'method'" + ) + cr.execute( + """ + CREATE INDEX IF NOT EXISTS + auditlog_log_line_method_index ON auditlog_log_line (method); + CREATE INDEX IF NOT EXISTS + auditlog_log_line_user_id_index ON auditlog_log_line (user_id); + CREATE INDEX IF NOT EXISTS + auditlog_log_line_model_id_index ON auditlog_log_line (model_id); + CREATE INDEX IF NOT EXISTS + auditlog_log_line_res_id_index ON auditlog_log_line (res_id); + """ + ) + logger.info( + "Preemtive fill of auditlog_log_line columns: 'method', user_id, res_id, model_id" + ) + cr.execute( + """ + UPDATE auditlog_log_line aline + SET method = al.method, user_id = al.user_id , model_id = al.model_id, res_id = al.res_id + FROM auditlog_log al + WHERE al.id = aline.log_id; + """ + ) + logger.info("Successfully updated auditlog tables") diff --git a/auditlog_security/models/__init__.py b/auditlog_security/models/__init__.py new file mode 100644 index 00000000000..5b1ed36f36a --- /dev/null +++ b/auditlog_security/models/__init__.py @@ -0,0 +1,7 @@ +# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). + +from . import auditlog_rule +from . import auditlog_line_access_rule +from . import ir_rule +from . import auditlog_log_line + diff --git a/auditlog_security/models/auditlog_line_access_rule.py b/auditlog_security/models/auditlog_line_access_rule.py new file mode 100644 index 00000000000..573ac55b2b1 --- /dev/null +++ b/auditlog_security/models/auditlog_line_access_rule.py @@ -0,0 +1,121 @@ +# Copyright 2021 Therp B.V. +# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). + +from odoo import exceptions, models, fields, api, modules, _ +from odoo.addons.auditlog.models.rule import FIELDS_BLACKLIST + + +class AuditlogLineAccessRule(models.Model): + _name = "auditlog.line.access.rule" + + name = fields.Char() + + field_ids = fields.Many2many("ir.model.fields") + group_ids = fields.Many2many( + "res.groups", + help="""Groups that will be allowed to see the logged fields, if left empty + default will be all users with a login""", + ) + model_id = fields.Many2one( + "ir.model", related="auditlog_rule_id.model_id", readonly=True + ) + auditlog_rule_id = fields.Many2one( + "auditlog.rule", "auditlog_access_rule_ids", readonly=True, ondelete="cascade" + ) + state = fields.Selection(related="auditlog_rule_id.state", readonly=True) + + def needs_rule(self): + self.ensure_one() + return bool(self.group_ids) + + def get_linked_rules(self): + return self.env["ir.rule"].search( + [("auditlog_line_access_rule_id", "in", self.ids)] + ) + + def unlink(self): + to_delete = self.get_linked_rules() + res = super(AuditlogLineAccessRule, self).unlink() + if res: + res = res and to_delete.unlink() + return res + + def add_default_group_if_needed(self): + self.ensure_one() + res = False + if not self.group_ids and self.field_ids: + res = self.with_context(no_iter=True).write( + {"group_ids": [(6, 0, [self.env.ref("base.group_user").id])]} + ) + return res + + @api.model + def create(self, vals): + res = super(AuditlogLineAccessRule, self).create(vals) + res.add_default_group_if_needed() + res.regenerate_rules() + return res + + @api.multi + def write(self, vals): + res = super(AuditlogLineAccessRule, self).write(vals) + for this in self: + added = this.add_default_group_if_needed() + if ( + any( + [ + x in vals + for x in ("group_ids", "field_ids", "model_id", "all_fields") + ] + ) + or added + ): + this.regenerate_rules() + + return res + + def remove_rules(self): + for this in self: + this.get_linked_rules().unlink() + + def regenerate_rules(self): + for this in self: + this.remove_rules() + dict_values = this._prepare_rule_values() + for values in dict_values: + self.env["ir.rule"].create(values) + + def _prepare_rule_values(self): + self.ensure_one() + if not self.needs_rule(): + return [] + domain_force = "[" + " ('log_id.model_id' , '=', %s)," % ( + self.model_id.id + ) + if self.field_ids: + domain_force = "[('field_id', 'in', %s)]" % (self.field_ids.ids) + model = self.env.ref("auditlog.model_auditlog_log_line") + else: + domain_force = "[('model_id', '=', %s)]" % (self.model_id.id) + model = self.env.ref("auditlog.model_auditlog_log") + auditlog_security_group = self.env.ref( + 'auditlog_security.group_can_view_audit_logs') + return [ + { + "name": "auditlog_extended_%s" % self.id, + "model_id": model.id, + "groups": [(6, 0, self.group_ids.ids)], + "perm_read": True, + "domain_force": domain_force, + "auditlog_line_access_rule_id": self.id, + }, + { + "name": "auditlog_extended_%s" % self.id, + "model_id": model.id, + "groups": [(6, 0, [auditlog_security_group.id])], + "perm_read": True, + "domain_force": [(1, '=', 1)], + "auditlog_line_access_rule_id": self.id, + }] + + diff --git a/auditlog_security/models/auditlog_log_line.py b/auditlog_security/models/auditlog_log_line.py new file mode 100644 index 00000000000..e7698e2c2cf --- /dev/null +++ b/auditlog_security/models/auditlog_log_line.py @@ -0,0 +1,47 @@ +# Copyright 2022 Therp B.V. +# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). + +from odoo import api, exceptions, models, fields + + +class AuditlogLogLine(models.Model): + _inherit = 'auditlog.log.line' + _order = "create_date desc" + + user_id = fields.Many2one( + 'res.users', + compute="compute_user_id", + store=True, + index=True, + string="User", + ) + method = fields.Char("Method", compute='compute_method', store=True, index=True) + model_id = fields.Many2one( + "ir.model", + compute='compute_model_id', + store=True, + index=True) + res_id = fields.Integer( + compute='compute_res_id', + store=True, + index=True) + + @api.depends('log_id.method') + def compute_method(self): + for this in self: + this.method=this.log_id.method + + @api.depends('log_id.user_id') + def compute_user_id(self): + for this in self: + this.user_id=this.log_id.user_id + + @api.depends('log_id.model_id') + def compute_model_id(self): + for this in self: + this.model_id=this.log_id.model_id + + @api.depends('log_id.res_id') + def compute_res_id(self): + for this in self: + this.res_id=this.log_id.res_id diff --git a/auditlog_security/models/auditlog_rule.py b/auditlog_security/models/auditlog_rule.py new file mode 100644 index 00000000000..76ac9003648 --- /dev/null +++ b/auditlog_security/models/auditlog_rule.py @@ -0,0 +1,127 @@ +# Copyright 2021 Therp B.V. +# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). + +from odoo import exceptions, models, fields, api, modules, _, tools +from odoo.addons.auditlog.models.rule import FIELDS_BLACKLIST +from odoo.exceptions import ValidationError, UserError + +class AuditlogRule(models.Model): + _inherit = "auditlog.rule" + + auditlog_line_access_rule_ids = fields.One2many( + "auditlog.line.access.rule", "auditlog_rule_id", ondelete="cascade" + ) + server_action_id = fields.Many2one('ir.actions.server', "Server Action",) + log_selected_fields_only = fields.Boolean( + default=True, + help="Log only the selected fields, to save space avoid large DB data.") + + @api.constrains('model_id') + def unique_model(self): + if self.search_count([('model_id', '=', self.model_id.id)]) > 1: + raise ValidationError("A rule for this model already exists") + + @api.model + @tools.ormcache('model_name') + def _get_field_names_of_rule(self, model_name): + """ Memory-cached list of fields per rule """ + rule = self.env['auditlog.rule'].sudo().search( + [('model_id.model', '=', model_name)], limit=1) + if rule.auditlog_line_access_rule_ids: + return rule.mapped( + 'auditlog_line_access_rule_ids.field_ids.name') + return [] + + @api.model + @tools.ormcache('model_name') + def _get_log_selected_fields_only(self, model_name): + """ Memory-cached translation of model to rule """ + rule = self.env['auditlog.rule'].sudo().search( + [('model_id.model', '=', model_name)], limit=1) + return rule.log_selected_fields_only + + @api.model + def get_auditlog_fields(self, model): + res = super(AuditlogRule, self).get_auditlog_fields(model) + if self._get_log_selected_fields_only(model._name): + selected_field_names = self._get_field_names_of_rule(model._name) + # we re-use the checks on non-stored fields from super. + res = [x for x in selected_field_names if x in res] + return res + + @api.multi + def write(self, values): + cache_invalidating_fields = [ + "state", + "auditlog_line_access_rule_ids", + "log_selected_fields_only", + ] + if any([field in values.keys() for field in cache_invalidating_fields]): + # clear cache for all ormcache methods. + self.clear_caches() + return super(AuditlogRule, self).write(values) + + @api.onchange("model_id") + def onchange_model_id(self): + # if model changes we must wipe out all field ids + self.auditlog_line_access_rule_ids.unlink() + + @api.model + def _get_view_log_lines_action(self): + assert(self.env.context.get('active_model')) + assert(self.env.context.get('active_ids')) + model = self.env['ir.model'].sudo().search([ + ('model', '=', self.env.context.get('active_model')) + ]) + domain = [ + ('model_id', '=', model.id), + ('res_id', 'in', self.env.context.get('active_ids')), + ] + return { + "name": _("View Log Lines"), + "res_model": "auditlog.log.line", + "view_mode": "tree,form", + "view_id": False, + "domain": domain, + "type": "ir.actions.act_window", + } + + @api.multi + def _create_server_action(self): + self.ensure_one() + code = \ + "action = env['auditlog.rule']._get_view_log_lines_action()" + server_action = self.env['ir.actions.server'].sudo().create({ + 'name': "View Log Lines", + 'model_id': self.model_id.id, + 'state': "code", + 'code': code + }) + self.write({ + 'server_action_id': server_action.id + }) + return server_action + + @api.multi + def subscribe(self): + for rule in self: + server_action = rule._create_server_action() + server_action.create_action() + res = super(AuditlogRule, self).subscribe() + for rule in self: + rule.auditlog_line_access_rule_ids.regenerate_rules() + # rule now will have "View Log" Action, make that visible only for admin + if res: + self.action_id.write({ + 'groups_id': [(6, 0, [self.env.ref('base.group_system').id])] + }) + return res + + @api.multi + def unsubscribe(self): + for rule in self: + rule.auditlog_line_access_rule_ids.remove_rules() + for rule in self: + rule.server_action_id.unlink() + return super(AuditlogRule, self).unsubscribe() + diff --git a/auditlog_security/models/ir_rule.py b/auditlog_security/models/ir_rule.py new file mode 100644 index 00000000000..665b58f0507 --- /dev/null +++ b/auditlog_security/models/ir_rule.py @@ -0,0 +1,16 @@ +# Copyright 2021 Therp B.V. +# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). + +from odoo import exceptions, models, fields, api, _ + + +class IrRule(models.Model): + _inherit = "ir.rule" + + auditlog_line_access_rule_id = fields.Many2one( + "auditlog.line.access.rule", + required=False, + index=True, + ondelete='cascade', + help="Auditlog line access Rule that generated this ir.rule", + ) diff --git a/auditlog_security/readme/CONTRIBUTORS.rst b/auditlog_security/readme/CONTRIBUTORS.rst new file mode 100644 index 00000000000..addcc3f4a2b --- /dev/null +++ b/auditlog_security/readme/CONTRIBUTORS.rst @@ -0,0 +1 @@ +* Giovanni Francesco Capalbo diff --git a/auditlog_security/readme/CREDITS.rst b/auditlog_security/readme/CREDITS.rst new file mode 100644 index 00000000000..e69de29bb2d diff --git a/auditlog_security/readme/DESCRIPTION.rst b/auditlog_security/readme/DESCRIPTION.rst new file mode 100644 index 00000000000..2d056774e16 --- /dev/null +++ b/auditlog_security/readme/DESCRIPTION.rst @@ -0,0 +1,3 @@ +This module allows extends auditlog, allowing specific log lines to be viewed only +by users belonging to specific views, while all other lines are allowed only to +administrator. diff --git a/auditlog_security/readme/ROADMAP.rst b/auditlog_security/readme/ROADMAP.rst new file mode 100644 index 00000000000..8b137891791 --- /dev/null +++ b/auditlog_security/readme/ROADMAP.rst @@ -0,0 +1 @@ + diff --git a/auditlog_security/readme/USAGE.rst b/auditlog_security/readme/USAGE.rst new file mode 100644 index 00000000000..f4cfaeca2cf --- /dev/null +++ b/auditlog_security/readme/USAGE.rst @@ -0,0 +1,11 @@ +Go to `Settings / Technical / Audit / Rules` to subscribe rules. A rule defines +which operations to log for a given data model. +The rule is now extended with a new field permission_ids, that tells us wich groups will +be allowed to read the lines produced by this rule. +If permission_ids is left empty, the default will be: +"auditlog lines visible only by user in Settings group, which is the default +for the auditlog module" + + +Then, check logs in the `Settings / Technical / Audit / Logs` menu. You can +group them by user sessions, date, data model , HTTP requests. diff --git a/auditlog_security/security/ir.model.access.csv b/auditlog_security/security/ir.model.access.csv new file mode 100644 index 00000000000..eba2422b41f --- /dev/null +++ b/auditlog_security/security/ir.model.access.csv @@ -0,0 +1,3 @@ +id,name,model_id:id,group_id:id,perm_read,perm_write,perm_create,perm_unlink +access_auditlog_log_line_user,auditlog_log_line_user,auditlog.model_auditlog_log_line,base.group_user,1,0,0,0 +access_auditlog_line_access_rule_admin,auditlog_line_access_rule_admin,model_auditlog_line_access_rule,base.group_erp_manager,1,1,1,1 \ No newline at end of file diff --git a/auditlog_security/security/ir_rule.xml b/auditlog_security/security/ir_rule.xml new file mode 100644 index 00000000000..d783eb6f6d2 --- /dev/null +++ b/auditlog_security/security/ir_rule.xml @@ -0,0 +1,15 @@ + + + + + Nobody can read by default + + [(0, '=', 1)] + + + + + + + + diff --git a/auditlog_security/security/res_groups.xml b/auditlog_security/security/res_groups.xml new file mode 100644 index 00000000000..2b4fd7171c9 --- /dev/null +++ b/auditlog_security/security/res_groups.xml @@ -0,0 +1,6 @@ + + + + View Audit Logs + + diff --git a/auditlog_security/static/description/index.html b/auditlog_security/static/description/index.html new file mode 100644 index 00000000000..03f14d1e6be --- /dev/null +++ b/auditlog_security/static/description/index.html @@ -0,0 +1,438 @@ + + + + + + +Audit Log User Permissions + + + +
+

Audit Log User Permissions

+ + +

Beta License: AGPL-3 OCA/server-tools Translate me on Weblate Try me on Runbot

+

This module allows extends auditlog, allowing specific log lines to be viewed only +by users belonging to specific views, while all other lines are allowed only to +administrator.

+

Table of contents

+ +
+

Usage

+

Go to Settings / Technical / Audit / Rules to subscribe rules. A rule defines +which operations to log for a given data model. +The rule is now extended with a new field permission_ids, that tells us wich groups will +be allowed to read the lines produced by this rule. +If permission_ids is left empty, the default will be: +“auditlog lines visible only by user in Settings group, which is the default +for the auditlog module”

+

Then, check logs in the Settings / Technical / Audit / Logs menu. You can +group them by user sessions, date, data model , HTTP requests.

+
+ +
+

Bug Tracker

+

Bugs are tracked on GitHub Issues. +In case of trouble, please check there if your issue has already been reported. +If you spotted it first, help us smashing it by providing a detailed and welcomed +feedback.

+

Do not contact contributors directly about support or help with technical issues.

+
+
+

Credits

+
+

Authors

+
    +
  • Therp B.V.
  • +
+
+
+

Contributors

+ +
+
+

Maintainers

+

This module is maintained by the OCA.

+Odoo Community Association +

OCA, or the Odoo Community Association, is a nonprofit organization whose +mission is to support the collaborative development of Odoo features and +promote its widespread use.

+

This module is part of the OCA/server-tools project on GitHub.

+

You are welcome to contribute. To learn how please visit https://odoo-community.org/page/Contribute.

+
+
+
+ + diff --git a/auditlog_security/views/auditlog_view.xml b/auditlog_security/views/auditlog_view.xml new file mode 100644 index 00000000000..3050c1d7517 --- /dev/null +++ b/auditlog_security/views/auditlog_view.xml @@ -0,0 +1,151 @@ + + + + auditlog.log.form + auditlog.log + + + + false + + + + + + auditlog.log.form + auditlog.log + + + + false + + + + + + + + + + + + + auditlog.log.line.form + auditlog.log.line + + + + + + + + + + + + + + + + + + + auditlog.log.line.tree + auditlog.log.line + + + + + + + + + + + + + + View Log Lines + ir.actions.act_window + auditlog.log.line + tree,form + + + + + + + auditlog rule form extension + auditlog.rule + + + + +
+

+ Add fields here to make any changes to them (audit log lines) + visible to members of the selected groups. +

+
+
+ + + + + + + + + + +
+ + + + + + + + + +
+
+
+
+
+
+ + + auditlog rule tree extension + auditlog.rule + + + + + + + + + + + + + + +
diff --git a/maintainer-tools b/maintainer-tools new file mode 160000 index 00000000000..7d8a9f9ad73 --- /dev/null +++ b/maintainer-tools @@ -0,0 +1 @@ +Subproject commit 7d8a9f9ad73db0976fb03cbee43d953bc29b89e9