Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
124 changes: 124 additions & 0 deletions auth_user_role/README.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
========================
360 ERP - Auth User Role
========================

..
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!! This file is generated by oca-gen-addon-readme !!
!! changes will be overwritten. !!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!! source digest: sha256:6b4bcdd74e55d4277803a74f7ac68e4bc51c14d2c4dec736cdfd1dea0ec9ee20
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

.. |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-LGPL--3-blue.png
:target: http://www.gnu.org/licenses/lgpl-3.0-standalone.html
:alt: License: LGPL-3
.. |badge3| image:: https://img.shields.io/badge/github-OCA%2Fserver--auth-lightgray.png?logo=github
:target: https://github.com/OCA/server-auth/tree/18.0/auth_user_role
:alt: OCA/server-auth
.. |badge4| image:: https://img.shields.io/badge/weblate-Translate%20me-F47D42.png
:target: https://translation.odoo-community.org/projects/server-auth-18-0/server-auth-18-0-auth_user_role
:alt: Translate me on Weblate
.. |badge5| image:: https://img.shields.io/badge/runboat-Try%20me-875A7B.png
:target: https://runboat.odoo-community.org/builds?repo=OCA/server-auth&target_branch=18.0
:alt: Try me on Runboat

|badge1| |badge2| |badge3| |badge4| |badge5|

This module provides a generic engine to map Identity Provider (IdP)
attributes to Odoo user roles. It acts as an abstraction layer built on
top of the ``base_user_role`` module.

By itself, this module does not handle authentication. Instead, it is
designed to be triggered by specialized "glue" modules (e.g., SAML,
OAuth, LDAP) during the login process. It evaluates incoming identity
payloads against a set of configured global rules and dynamically
provisions or revokes user roles.

**Table of contents**

.. contents::
:local:

Configuration
=============

To configure role mappings:

1. Navigate to **Settings > Users & Companies > Identity Role
Mappings**.
2. Create a new mapping rule.
3. Define the **Identity Attribute**: Enter the exact payload attribute
key provided by your IdP (e.g., ``department``, ``groups``,
``eduPersonAffiliation``).
4. Select the **Operator**:

- **equals**: The payload value must exactly match the defined value.
- **contains**: The payload value must contain the defined value
(useful for comma-separated lists or longer strings).

5. Define the **Value** you expect to receive from the IdP.
6. Select the **Role** (from ``base_user_role``) that should be assigned
when the condition is met.

Usage
=====

There is no direct user interaction required for this module. Once
configured, the evaluation and assignment of roles happen automatically
in the background whenever an integrated authentication provider
triggers the ``evaluate_and_apply_auth_roles`` method during user
sign-in.

All role grants, reactivations, and revocations are automatically logged
in the Odoo server logs for security auditing.

Bug Tracker
===========

Bugs are tracked on `GitHub Issues <https://github.com/OCA/server-auth/issues>`_.
In case of trouble, please check there if your issue has already been reported.
If you spotted it first, help us to smash it by providing a detailed and welcomed
`feedback <https://github.com/OCA/server-auth/issues/new?body=module:%20auth_user_role%0Aversion:%2018.0%0A%0A**Steps%20to%20reproduce**%0A-%20...%0A%0A**Current%20behavior**%0A%0A**Expected%20behavior**>`_.

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

Credits
=======

Authors
-------

* 360 ERP

Contributors
------------

- Andrea Stirpe

Other credits
-------------

The development of this module has been financially supported by:

- 360 ERP

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-auth <https://github.com/OCA/server-auth/tree/18.0/auth_user_role>`_ project on GitHub.

You are welcome to contribute. To learn how please visit https://odoo-community.org/page/Contribute.
4 changes: 4 additions & 0 deletions auth_user_role/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# Copyright 2026 360ERP (<https://www.360erp.com>)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).

from . import models
17 changes: 17 additions & 0 deletions auth_user_role/__manifest__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# Copyright 2026 360ERP (<https://www.360erp.com>)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).

{
"name": "360 ERP - Auth User Role",
"version": "18.0.1.0.0",
"author": "360 ERP, Odoo Community Association (OCA)",
"website": "https://github.com/OCA/server-auth",
"license": "AGPL-3",
"depends": [
"base_user_role",
],
"data": [
"security/ir.model.access.csv",
"views/auth_user_role_mapping_views.xml",
],
}
6 changes: 6 additions & 0 deletions auth_user_role/models/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
# Copyright 2026 360ERP (<https://www.360erp.com>)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).

from . import auth_user_role_mapping
from . import res_config_settings
from . import res_users
61 changes: 61 additions & 0 deletions auth_user_role/models/auth_user_role_mapping.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
# Copyright 2026 360ERP (<https://www.360erp.com>)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).

from odoo import api, fields, models, tools


class AuthUserRoleMapping(models.Model):
_name = "auth.user.role.mapping"
_description = "Identity Role Mapping"
_rec_name = "attribute"
_order = "attribute"

attribute = fields.Char(
string="Identity Attribute",
help=(
"The payload attribute to check (e.g., department, "
"groups, eduPersonAffiliation)."
),
required=True,
)
operator = fields.Selection(
selection=[("equals", "equals"), ("contains", "contains")],
default="equals",
required=True,
help="The operator to check the attribute against the value.",
)
value = fields.Char(help="The value to check the attribute against.", required=True)
role_id = fields.Many2one(
"res.users.role",
help="The Odoo role to assign.",
required=True,
ondelete="cascade",
)

@api.model
@tools.ormcache()
def _get_all_mappings_cached(self):
"""Fetch all mappings and cache them as native dicts for fast evaluation."""
mappings = self.sudo().search([])
return [
{
"attribute": m.attribute,
"operator": m.operator,
"value": m.value,
"role_id": m.role_id.id,
}
for m in mappings
]

@api.model_create_multi
def create(self, vals_list):
self.env.registry.clear_cache()
return super().create(vals_list)

def write(self, vals):
self.env.registry.clear_cache()
return super().write(vals)

def unlink(self):
self.env.registry.clear_cache()
return super().unlink()
19 changes: 19 additions & 0 deletions auth_user_role/models/res_config_settings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# Copyright 2026 360ERP (<https://www.360erp.com>)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).

from odoo import fields, models


class ResConfigSettings(models.TransientModel):
_inherit = "res.config.settings"

auth_user_role_strict_sync = fields.Boolean(
string="Strict Identity Role Synchronization",
config_parameter="auth_user_role.strict_sync",
default=True,
help=(
"If enabled globally, any Odoo roles manually assigned to a user will be "
"removed if they are not explicitly provided by the "
"Identity Provider payload."
),
)
107 changes: 107 additions & 0 deletions auth_user_role/models/res_users.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
# Copyright 2026 360ERP (<https://www.360erp.com>)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).

import logging

from odoo import models

_logger = logging.getLogger(__name__)


class ResUser(models.Model):
_inherit = "res.users"

def _get_mapped_roles(self, identity_payload):
"""Helper to evaluate the identity payload against role mappings."""
roles_to_add = set()
if not identity_payload:
return roles_to_add

cached_mappings = self.env["auth.user.role.mapping"]._get_all_mappings_cached()

for mapping in cached_mappings:
if mapping["attribute"] not in identity_payload:
continue

attribute_values = identity_payload.get(mapping["attribute"])
if not isinstance(attribute_values, list):
attribute_values = [attribute_values]

for attr_val in attribute_values:
attr_str = str(attr_val)
if mapping["operator"] == "equals" and attr_str == mapping["value"]:
roles_to_add.add(mapping["role_id"])
elif mapping["operator"] == "contains" and mapping["value"] in attr_str:
roles_to_add.add(mapping["role_id"])

return roles_to_add

def evaluate_and_apply_auth_roles(self, identity_payload, strict_sync=None):
"""
Abstraction layer to evaluate an identity payload against global mappings
and apply the resulting roles to the user.
"""
self.ensure_one()

# Fall back to global system parameter if not explicitly overridden
if strict_sync is None:
strict_sync = (
self.env["ir.config_parameter"]
.sudo()
.get_param("auth_user_role.strict_sync", "True")
== "True"
)

roles_to_add = self._get_mapped_roles(identity_payload)

existing_lines = self.role_line_ids
existing_role_ids = set(existing_lines.mapped("role_id").ids)
active_role_ids = set(self._get_enabled_roles().mapped("role_id").ids)

commands = []
roles_removed_log = []
roles_added_log = []

if strict_sync:
roles_to_remove = existing_role_ids - roles_to_add
if roles_to_remove:
lines_to_remove = existing_lines.filtered(
lambda el: el.role_id.id in roles_to_remove
)
for line in lines_to_remove:
commands.append((2, line.id, 0))
roles_removed_log.append(line.role_id.name)

for role_id in roles_to_add:
if role_id not in existing_role_ids:
commands.append((0, 0, {"role_id": role_id}))
role = self.env["res.users.role"].browse(role_id)
roles_added_log.append(role.name)
elif role_id not in active_role_ids:
line_to_activate = existing_lines.filtered(
lambda el, rid=role_id: el.role_id.id == rid
)
if line_to_activate:
commands.append((1, line_to_activate[0].id, {"date_to": False}))
role = self.env["res.users.role"].browse(role_id)
roles_added_log.append(f"{role.name} (Reactivated)")

if commands:
self.write({"role_line_ids": commands})
if roles_removed_log:
_logger.info(
"Identity Sync - Removed roles from user %s: %s",
self.login,
", ".join(roles_removed_log),
)
if roles_added_log:
_logger.info(
"Identity Sync - Granted roles to user %s: %s",
self.login,
", ".join(roles_added_log),
)

if strict_sync:
self.set_groups_from_roles(force=True)

return list(roles_to_add)
3 changes: 3 additions & 0 deletions auth_user_role/pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
[build-system]
requires = ["whool"]
build-backend = "whool.buildapi"
10 changes: 10 additions & 0 deletions auth_user_role/readme/CONFIGURE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
To configure role mappings:

1. Navigate to **Settings > Users & Companies > Identity Role Mappings**.
2. Create a new mapping rule.
3. Define the **Identity Attribute**: Enter the exact payload attribute key provided by your IdP (e.g., `department`, `groups`, `eduPersonAffiliation`).
4. Select the **Operator**:
* **equals**: The payload value must exactly match the defined value.
* **contains**: The payload value must contain the defined value (useful for comma-separated lists or longer strings).
5. Define the **Value** you expect to receive from the IdP.
6. Select the **Role** (from `base_user_role`) that should be assigned when the condition is met.
1 change: 1 addition & 0 deletions auth_user_role/readme/CONTRIBUTORS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* Andrea Stirpe
3 changes: 3 additions & 0 deletions auth_user_role/readme/CREDITS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
The development of this module has been financially supported by:

* 360 ERP
6 changes: 6 additions & 0 deletions auth_user_role/readme/DESCRIPTION.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
This module provides a generic engine to map Identity Provider (IdP) attributes to Odoo user roles.
It acts as an abstraction layer built on top of the `base_user_role` module.

By itself, this module does not handle authentication.
Instead, it is designed to be triggered by specialized "glue" modules (e.g., SAML, OAuth, LDAP) during the login process.
It evaluates incoming identity payloads against a set of configured global rules and dynamically provisions or revokes user roles.
4 changes: 4 additions & 0 deletions auth_user_role/readme/USAGE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
There is no direct user interaction required for this module.
Once configured, the evaluation and assignment of roles happen automatically in the background whenever an integrated authentication provider triggers the `evaluate_and_apply_auth_roles` method during user sign-in.

All role grants, reactivations, and revocations are automatically logged in the Odoo server logs for security auditing.
2 changes: 2 additions & 0 deletions auth_user_role/security/ir.model.access.csv
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
id,name,model_id:id,group_id:id,perm_read,perm_write,perm_create,perm_unlink
access_auth_user_role_mapping,auth.user.role.mapping,model_auth_user_role_mapping,base.group_system,1,1,1,1
Binary file added auth_user_role/static/description/icon.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Loading