diff --git a/base_external_system_oauth/README.rst b/base_external_system_oauth/README.rst new file mode 100644 index 000000000..4a74cb1c5 --- /dev/null +++ b/base_external_system_oauth/README.rst @@ -0,0 +1,85 @@ +==================================== +Base External System - oauth systems +==================================== + +.. + !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + !! This file is generated by oca-gen-addon-readme !! + !! changes will be overwritten. !! + !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + !! source digest: sha256:698f8077f5eedd2e8893d1a01b9dee77c62c30a45b74dddfd092ae16cd8312df + !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + +.. |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--backend-lightgray.png?logo=github + :target: https://github.com/OCA/server-backend/tree/16.0/base_external_system_oauth + :alt: OCA/server-backend +.. |badge4| image:: https://img.shields.io/badge/weblate-Translate%20me-F47D42.png + :target: https://translation.odoo-community.org/projects/server-backend-16-0/server-backend-16-0-base_external_system_oauth + :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-backend&target_branch=16.0 + :alt: Try me on Runboat + +|badge1| |badge2| |badge3| |badge4| |badge5| + +This module adds the oauth authentication method to connect to remote +systems. + +**Table of contents** + +.. contents:: + :local: + +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 to smash it by providing a detailed and welcomed +`feedback `_. + +Do not contact contributors directly about support or help with technical issues. + +Credits +======= + +Authors +------- + +* Therp BV + +Contributors +------------ + +- Ronald Portier + +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. + +.. |maintainer-NL66278| image:: https://github.com/NL66278.png?size=40px + :target: https://github.com/NL66278 + :alt: NL66278 + +Current `maintainer `__: + +|maintainer-NL66278| + +This module is part of the `OCA/server-backend `_ project on GitHub. + +You are welcome to contribute. To learn how please visit https://odoo-community.org/page/Contribute. diff --git a/base_external_system_oauth/__init__.py b/base_external_system_oauth/__init__.py new file mode 100644 index 000000000..83e553ac4 --- /dev/null +++ b/base_external_system_oauth/__init__.py @@ -0,0 +1,3 @@ +# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). + +from . import models diff --git a/base_external_system_oauth/__manifest__.py b/base_external_system_oauth/__manifest__.py new file mode 100644 index 000000000..26961ca8d --- /dev/null +++ b/base_external_system_oauth/__manifest__.py @@ -0,0 +1,25 @@ +# Copyright 2023-2024 Therp BV . +# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). + +{ + "name": "Base External System - oauth systems", + "summary": "Connect to external systems through oauth authentication.", + "version": "18.0.1.0.0", + "category": "Base", + "website": "https://github.com/OCA/server-backend", + "author": "Therp BV, Odoo Community Association (OCA)", + "maintainers": ["NL66278"], + "license": "AGPL-3", + "depends": [ + "auth_oauth", + "base_external_system_http", + ], + "data": [ + "demo/auth_oauth_provider_demo.xml", + "demo/external_system_demo.xml", + "views/external_system.xml", + "views/auth_oauth_provider.xml", + ], + "application": False, + "installable": True, +} diff --git a/base_external_system_oauth/demo/auth_oauth_provider_demo.xml b/base_external_system_oauth/demo/auth_oauth_provider_demo.xml new file mode 100644 index 000000000..7f76bb5ee --- /dev/null +++ b/base_external_system_oauth/demo/auth_oauth_provider_demo.xml @@ -0,0 +1,19 @@ + + + + + + Demo oauth providerI + https://api.example.com/oauth2/api/v1/token + x + demo + api_example_com + Set client secret to value from provider + zocial + Log in to oauth token provider + + + diff --git a/base_external_system_oauth/demo/external_system_demo.xml b/base_external_system_oauth/demo/external_system_demo.xml new file mode 100644 index 000000000..933fb70f1 --- /dev/null +++ b/base_external_system_oauth/demo/external_system_demo.xml @@ -0,0 +1,15 @@ + + + + + Example system access with oauth athorization + external.system.adapter.oauth + https + api.example.com + + + + diff --git a/base_external_system_oauth/models/__init__.py b/base_external_system_oauth/models/__init__.py new file mode 100644 index 000000000..069e95a20 --- /dev/null +++ b/base_external_system_oauth/models/__init__.py @@ -0,0 +1,6 @@ +# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). + +from . import auth_oauth_provider +from . import external_system +from . import external_system_interaction_oauth_mixin +from . import external_system_adapter_oauth # uses mixin diff --git a/base_external_system_oauth/models/auth_oauth_provider.py b/base_external_system_oauth/models/auth_oauth_provider.py new file mode 100644 index 000000000..829ceb1ee --- /dev/null +++ b/base_external_system_oauth/models/auth_oauth_provider.py @@ -0,0 +1,98 @@ +# Copyright 2020-2024 Therp BV . +# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). +# pylint: disable=no-self-use +"""Provide extra functionality to use Microsoft oauth for applications.""" + +import logging + +import requests +from requests.auth import HTTPBasicAuth + +from odoo import _, fields, models +from odoo.exceptions import UserError + +_logger = logging.getLogger(__name__) # pylint: disable=invalid-name + + +class AuthOAuthProvider(models.Model): + """Abstract model to communicate with oauth authentication provider.""" + + _inherit = "auth.oauth.provider" + + tenant_id = fields.Char() + client_secret = fields.Char() + provider_type = fields.Selection( + selection=[ + ("demo", "DEMO Just for testing purposes"), + ("basic", "Use client_id and client_secret for basic Authentication"), + ("microsoft_client_secret", "Microsoft Client Secret Authentication"), + ], + default="demo", + help="Provider type determines the method to retrieve bearer token", + ) + + def action_test_get_token(self): + """Test wether we can get token using this configuration.""" + self.get_access_token() + + def get_access_token(self): + """Redirect to method specific to provider type.""" + self.ensure_one() + handler = getattr(self, "_get_access_token_" + self.provider_type) + return handler() + + def _get_access_token_demo(self): + """Get fixed access token using basic authentication.""" + if self.client_id == "api_example_com" and self.client_secret == "the-secret": + return "you_are_in" + raise UserError(_("Wrong client_id or client_secret")) + + def _get_access_token_basic(self): + """Get access token using basic authentication.""" + login_params = { + "grant_type": "client_credentials", + } + basic = HTTPBasicAuth(self.client_id, self.client_secret) + response = requests.post( + url=self.auth_endpoint, data=login_params, auth=basic, timeout=16 + ) + self._check_response(response) + return response.json()["access_token"] + + def _get_access_token_microsoft_client_secret(self): + """Get access token from Microsoft.""" + login_url = f"{self.auth_endpoint}/{self.tenant_id}{self.validation_endpoint}" + scope = self.scope % self.client_id + login_params = { + "client_id": self.client_id, + "scope": scope, + "tenant": self.tenant_id, + "grant_type": "client_credentials", + "client_secret": self.client_secret, + } + login_headers = {"Content-Type": "application/x-www-form-urlencoded"} + response = requests.post( + url=login_url, headers=login_headers, data=login_params, timeout=16 + ) + self._check_response(response) + return response.json()["access_token"] + + def _check_response(self, response): + """Check response from oauth provider.""" + if response.status_code != 200: + raise UserError( + _( + "Error at login to OAuth provider:\n" + "Status_code: %(status_code)s\n" + "Response: %(response)s" + ) + % { + "status_code": response.status_code, + "response": response.content, + } + ) + _logger.debug( + "Oauth status_code %s, response content %s", + response.status_code, + response.content, + ) diff --git a/base_external_system_oauth/models/external_system.py b/base_external_system_oauth/models/external_system.py new file mode 100644 index 000000000..b5569341d --- /dev/null +++ b/base_external_system_oauth/models/external_system.py @@ -0,0 +1,15 @@ +# Copyright 2023 Therp BV . +# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). + +from odoo import fields, models + + +class ExternalSystem(models.Model): + """Extend base external system""" + + _inherit = "external.system" + + oauth_definition_id = fields.Many2one( + comodel_name="auth.oauth.provider", + help="Use this if authorisation done by oauth provider", + ) diff --git a/base_external_system_oauth/models/external_system_adapter_oauth.py b/base_external_system_oauth/models/external_system_adapter_oauth.py new file mode 100644 index 000000000..0c9a2bf2a --- /dev/null +++ b/base_external_system_oauth/models/external_system_adapter_oauth.py @@ -0,0 +1,55 @@ +# Copyright 2023-2024 Therp BV. +# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). +"""Extend external system with oauth authentication.""" + +from odoo import models + + +class ExternalSystemAdapterOAuth(models.AbstractModel): + """This is an Interface implementing the OAuth module.""" + + _name = "external.system.adapter.oauth" + _inherit = [ + "external.system.adapter.http", + "external.system.interaction.oauth.mixin", + ] + _description = __doc__ + + def get_token(self): + """Get token from adapter_memory.""" + return self.env.context["adapter_memory"].get("token", None) + + def set_token(self, value): + """Store token in adapter_memor.""" + self.env.context["adapter_memory"]["token"] = value + + def del_token(self): + """Get system from environment.""" + if "token" in self.env.context["adapter_memory"]: + del self.env.context["adapter_memory"]["token"] + + token = property(get_token, set_token, del_token) + + def external_get_client(self): + """Return token that can be used to access remote system.""" + client = super().external_get_client() + oauth = self.system_id.oauth_definition_id + self.token = oauth.get_access_token() + return client + + def external_destroy_client(self, client): + """Delete token from client.""" + del self.token + return super().external_destroy_client(client) + + def post(self, endpoint=None, data=None, json=None, **kwargs): + """Send post request.""" + headers = kwargs.pop("headers", {}) + self._set_headers(headers) + return super().post( + endpoint=endpoint, data=data, json=json, headers=headers, **kwargs + ) + + def _get_token(self): + """Trivial implementation.""" + return self.token diff --git a/base_external_system_oauth/models/external_system_interaction_oauth_mixin.py b/base_external_system_oauth/models/external_system_interaction_oauth_mixin.py new file mode 100644 index 000000000..de5a9bf7f --- /dev/null +++ b/base_external_system_oauth/models/external_system_interaction_oauth_mixin.py @@ -0,0 +1,48 @@ +# Copyright 2023-2024 Therp BV. +# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). +"""Use this for json request communication with token authorization.""" + +from odoo import _, models +from odoo.exceptions import UserError + + +class ExternalSystemInteractionOauthMixin(models.AbstractModel): + """This contains method to interact with http systems using oauth authentication.""" + + _name = "external.system.interaction.oauth.mixin" + _inherit = "external.system.interaction.mixin" + _description = __doc__ + + def post(self, endpoint=None, data=None, json=None, **kwargs): + """Send post request.""" + headers = kwargs.pop("headers", {}) + self._set_headers(headers) + return super().post( + endpoint=endpoint, data=data, json=json, headers=headers, **kwargs + ) + + def get_json(self, endpoint=None, params=None, **kwargs): + """Get json formatted data from remote system.""" + headers = kwargs.get("headers", {}) + self._set_headers(headers) + return super().get( + endpoint=endpoint, params=params, **dict(kwargs, headers=headers) + ) + + def _set_headers(self, headers): + """Set headers in keyword arguments.""" + headers["Content-Type"] = "application/json" + self._add_authorization_header(headers) + + def _add_authorization_header(self, headers): + """Add authorization header to the passed headers dictionary.""" + token = self._get_token() + if not token: + raise UserError( + _("Not able to get bearer token for system %s.") % self.name + ) + headers["Authorization"] = f"Bearer {token}" + + def _get_token(self): + """Need to override this with concrete implementation.""" + raise UserError(_("Methode _get_token needs concrete implementation")) diff --git a/base_external_system_oauth/pyproject.toml b/base_external_system_oauth/pyproject.toml new file mode 100644 index 000000000..4231d0ccc --- /dev/null +++ b/base_external_system_oauth/pyproject.toml @@ -0,0 +1,3 @@ +[build-system] +requires = ["whool"] +build-backend = "whool.buildapi" diff --git a/base_external_system_oauth/readme/CONTRIBUTORS.md b/base_external_system_oauth/readme/CONTRIBUTORS.md new file mode 100644 index 000000000..c2a6ea2eb --- /dev/null +++ b/base_external_system_oauth/readme/CONTRIBUTORS.md @@ -0,0 +1 @@ +- Ronald Portier \<\> diff --git a/base_external_system_oauth/readme/DESCRIPTION.md b/base_external_system_oauth/readme/DESCRIPTION.md new file mode 100644 index 000000000..2d8127886 --- /dev/null +++ b/base_external_system_oauth/readme/DESCRIPTION.md @@ -0,0 +1,2 @@ +This module adds the oauth authentication method to connect to remote +systems. diff --git a/base_external_system_oauth/static/description/index.html b/base_external_system_oauth/static/description/index.html new file mode 100644 index 000000000..9fdaf7b28 --- /dev/null +++ b/base_external_system_oauth/static/description/index.html @@ -0,0 +1,424 @@ + + + + + + +Base External System - oauth systems + + + +
+

Base External System - oauth systems

+ + +

Beta License: AGPL-3 OCA/server-backend Translate me on Weblate Try me on Runboat

+

This module adds the oauth authentication method to connect to remote +systems.

+

Table of contents

+ +
+

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 to smash it by providing a detailed and welcomed +feedback.

+

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

+
+
+

Credits

+
+

Authors

+
    +
  • Therp BV
  • +
+
+
+

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.

+

Current maintainer:

+

NL66278

+

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

+

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

+
+
+
+ + diff --git a/base_external_system_oauth/tests/__init__.py b/base_external_system_oauth/tests/__init__.py new file mode 100644 index 000000000..13c294063 --- /dev/null +++ b/base_external_system_oauth/tests/__init__.py @@ -0,0 +1,3 @@ +# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). + +from . import test_external_system diff --git a/base_external_system_oauth/tests/test_external_system.py b/base_external_system_oauth/tests/test_external_system.py new file mode 100644 index 000000000..5c3f3b004 --- /dev/null +++ b/base_external_system_oauth/tests/test_external_system.py @@ -0,0 +1,42 @@ +# Copyright 2024 Therp BV. +# License AGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). +from odoo.tests.common import TransactionCase + +ADAPTER_MODEL = "external.system.adapter.oauth" + + +class TestExternalSystem(TransactionCase): + @classmethod + def setUpClass(cls): + super().setUpClass() + cls.record = cls.env.ref( + "base_external_system_oauth.external_system_oauth_demo" + ) + cls.record.oauth_definition_id.write({"client_secret": "the-secret"}) + + def test_get_system_types(self): + """It should return at least the test record's interface.""" + system_type_oauth = self.env[ADAPTER_MODEL] + self.assertIn( + (system_type_oauth._name, system_type_oauth._description), + self.env["external.system"]._get_system_types(), + ) + + def test_client(self): + """The client should be the adapter class.""" + system_type_oauth = self.env[ADAPTER_MODEL] + with self.record.client() as client: + self.assertEqual(client, system_type_oauth) + # Client should have system_id property. + self.assertEqual(client.system_id, self.record) + + def test_action_test_connection(self): + """It should correctly connect to the remote system.""" + self.record.action_test_connection() + + def test_strip_empty_data(self): + """Strip data from structure.""" + data = {"bla": " ", "more_bla": []} + system_type_oauth = self.env[ADAPTER_MODEL] + stripped_data = system_type_oauth.strip_empty_data(data) + self.assertEqual(stripped_data, {"bla": ""}) diff --git a/base_external_system_oauth/views/auth_oauth_provider.xml b/base_external_system_oauth/views/auth_oauth_provider.xml new file mode 100644 index 000000000..5899c1de3 --- /dev/null +++ b/base_external_system_oauth/views/auth_oauth_provider.xml @@ -0,0 +1,24 @@ + + + + auth.oauth.provider form - tenant and secret fields + auth.oauth.provider + + + +
+
+
+ + + + + + +
+
diff --git a/base_external_system_oauth/views/external_system.xml b/base_external_system_oauth/views/external_system.xml new file mode 100644 index 000000000..2acfd6932 --- /dev/null +++ b/base_external_system_oauth/views/external_system.xml @@ -0,0 +1,13 @@ + + + + external.system form - oauth fields + external.system + + + + + + + +