From 0c8850c64fe9838165f995969fdf5c6e785dee56 Mon Sep 17 00:00:00 2001 From: "Ronald Portier (Therp BV)" Date: Thu, 19 Oct 2023 12:33:06 +0200 Subject: [PATCH 01/14] [ADD] base_external_system_oauth: new module --- base_external_system_oauth/__init__.py | 4 + base_external_system_oauth/__manifest__.py | 23 ++++ base_external_system_oauth/models/__init__.py | 6 + .../models/auth_oauth_provider.py | 90 +++++++++++++++ .../models/external_system.py | 16 +++ .../models/external_system_adapter_oauth.py | 106 ++++++++++++++++++ .../readme/CONTRIBUTORS.rst | 1 + .../readme/DESCRIPTION.rst | 2 + .../views/auth_oauth_provider.xml | 24 ++++ .../views/external_system.xml | 13 +++ 10 files changed, 285 insertions(+) create mode 100644 base_external_system_oauth/__init__.py create mode 100644 base_external_system_oauth/__manifest__.py create mode 100644 base_external_system_oauth/models/__init__.py create mode 100644 base_external_system_oauth/models/auth_oauth_provider.py create mode 100644 base_external_system_oauth/models/external_system.py create mode 100644 base_external_system_oauth/models/external_system_adapter_oauth.py create mode 100644 base_external_system_oauth/readme/CONTRIBUTORS.rst create mode 100644 base_external_system_oauth/readme/DESCRIPTION.rst create mode 100644 base_external_system_oauth/views/auth_oauth_provider.xml create mode 100644 base_external_system_oauth/views/external_system.xml diff --git a/base_external_system_oauth/__init__.py b/base_external_system_oauth/__init__.py new file mode 100644 index 000000000..494cc90f0 --- /dev/null +++ b/base_external_system_oauth/__init__.py @@ -0,0 +1,4 @@ +# -*- coding: utf-8 -*- +# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.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..d254a1010 --- /dev/null +++ b/base_external_system_oauth/__manifest__.py @@ -0,0 +1,23 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 trough oauth authentication.", + "version": "10.0.1.0.0", + "category": "Base", + "website": "https://github.com/OCA/server-tools", + "author": "Therp BV, Odoo Community Association (OCA)", + "license": "AGPL-3", + "application": False, + "installable": True, + "depends": [ + "auth_oauth", + "base_external_system_http", + ], + "data": [ + "views/external_system.xml", + "views/auth_oauth_provider.xml", + ], +} diff --git a/base_external_system_oauth/models/__init__.py b/base_external_system_oauth/models/__init__.py new file mode 100644 index 000000000..92ee85f41 --- /dev/null +++ b/base_external_system_oauth/models/__init__.py @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# 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_adapter_oauth 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..a6f57c72d --- /dev/null +++ b/base_external_system_oauth/models/auth_oauth_provider.py @@ -0,0 +1,90 @@ +# Copyright 2020 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=[ + ("basic", "Use client_id and client_secret for basic Authentication"), + ("microsoft_client_secret", "Microsoft Client Secret autehntication"), + ], + default="basic", + 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_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, params=login_params, auth=basic + ) + self._check_response(response) + return response.json()["access_token"] + + def _get_access_token_microsoft_client_secret(self): + """Get access token from Microsoft.""" + login_url = "%(auth_endpoint)s/%(tenant_id)s%(validation_endpoint)s" % { + "auth_endpoint": self.auth_endpoint, + "tenant_id": self.tenant_id, + "validation_endpoint": 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 + ) + 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..941ecd465 --- /dev/null +++ b/base_external_system_oauth/models/external_system.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# 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..4337bcc7a --- /dev/null +++ b/base_external_system_oauth/models/external_system_adapter_oauth.py @@ -0,0 +1,106 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Therp BV. +# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). +# pylint: disable=no-member +"""Extend external system with oauth authentication.""" +import json +import logging +import requests + +from odoo import _, api, models +from odoo.exceptions import UserError + +# You must initialize logging, otherwise you'll not see debug output. +logging.basicConfig() +logging.getLogger().setLevel(logging.DEBUG) +requests_log = logging.getLogger("requests.packages.urllib3") +requests_log.setLevel(logging.DEBUG) +requests_log.propagate = True + + +def strip_empty(data): + """Strip all empty data from nested datastructure.""" + if isinstance(data, dict): + return { + k: strip_empty(v) + for k, v in data.items() + if k and v + } + if isinstance(data, list): + return [strip_empty(item) for item in data if item] + if isinstance(data, tuple): + return tuple(strip_empty(item) for item in data if item) + if isinstance(data, set): + return {strip_empty(item) for item in data if item} + return strip_empty_spaces(data) + + +def strip_empty_spaces(string): + """Remove all whitespace from end of string like item.""" + if isinstance(string, str): + return string.strip() + return string + + +class ExternalSystemAdapterOAuth(models.AbstractModel): + """This is an Interface implementing the OAuth module.""" + + _name = "external.system.adapter.oauth" + _inherit = "external.system.adapter.http" + _description = "External System Adapter OAuth" + + token = None + + @api.multi + def external_get_client(self): + """Return token that can be used to access remote system.""" + client = super(ExternalSystemAdapterOAuth, self).external_get_client() + oauth = self.system_id.oauth_definition_id + self.token = oauth.get_access_token() + return client + + @api.multi + def external_destroy_client(self, client): + """Perform any logic necessary to destroy the client connection. + + Args: + client (mixed): The client that was returned by + ``external_get_client``. + """ + if self.token: + self.token = None + super(ExternalSystemAdapterOAuth, self).external_destroy_client(client) + + def post(self, endpoint=None, data=None, json=None, **kwargs): + """Send post request.""" + headers = kwargs.pop("headers", {}) + self._set_oauth_headers(headers) + return super( + ExternalSystemAdapterOAuth, self + ).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.""" + self._set_oauth_headers(**kwargs) + return super( + ExternalSystemAdapterOAuth, self + ).get(endpoint=endpoint, params=params, **kwargs) + + def _set_oauth_headers(self, headers): + """Set headers in keyword arguments.""" + self._check_token() + headers["Content-Type"] = "application/json" + self._add_authorization_header(headers) + + def _check_token(self): + """Check for connection authorization (we have a token).""" + if not self.token: + raise UserError(_("Not connected to external system %s.") % self.name) + + def _add_authorization_header(self, headers): + """Add authorization header to the passed headers dictionary.""" + headers["Authorization"] = "Bearer %(token)s" % {"token": self.token} + + def strip_empty_data(self, data): + """"Utility method that can be called on adapter to cleanup data.""" + return strip_empty(data) diff --git a/base_external_system_oauth/readme/CONTRIBUTORS.rst b/base_external_system_oauth/readme/CONTRIBUTORS.rst new file mode 100644 index 000000000..4e07c28e1 --- /dev/null +++ b/base_external_system_oauth/readme/CONTRIBUTORS.rst @@ -0,0 +1 @@ +* Ronald Portier diff --git a/base_external_system_oauth/readme/DESCRIPTION.rst b/base_external_system_oauth/readme/DESCRIPTION.rst new file mode 100644 index 000000000..16723bd3a --- /dev/null +++ b/base_external_system_oauth/readme/DESCRIPTION.rst @@ -0,0 +1,2 @@ +This module adds the oauth authentication method to connect +to remote systems. 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..17fff039a --- /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 + + + + + + + + From 7c68429688dabf09a5e7764af07a051d4a4a34fb Mon Sep 17 00:00:00 2001 From: Ronald Portier Date: Wed, 3 Apr 2024 11:00:07 +0200 Subject: [PATCH 02/14] [IMP] base_external_system_oauth: pre-commit stuff --- base_external_system_oauth/README.rst | 77 ++++ base_external_system_oauth/__init__.py | 1 - base_external_system_oauth/__manifest__.py | 1 - base_external_system_oauth/models/__init__.py | 1 - .../models/auth_oauth_provider.py | 1 - .../models/external_system.py | 1 - .../models/external_system_adapter_oauth.py | 23 +- .../static/description/index.html | 422 ++++++++++++++++++ 8 files changed, 507 insertions(+), 20 deletions(-) create mode 100644 base_external_system_oauth/README.rst create mode 100644 base_external_system_oauth/static/description/index.html diff --git a/base_external_system_oauth/README.rst b/base_external_system_oauth/README.rst new file mode 100644 index 000000000..3f9fb2c45 --- /dev/null +++ b/base_external_system_oauth/README.rst @@ -0,0 +1,77 @@ +==================================== +Base External System - oauth systems +==================================== + +.. + !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + !! This file is generated by oca-gen-addon-readme !! + !! changes will be overwritten. !! + !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + !! source digest: sha256:b7bcb98052072b585356539a42b3f52c0a030e9a943f1cb3ea63866911106c7e + !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + +.. |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/16.0/base_external_system_oauth + :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-16-0/server-tools-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-tools&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. + +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/base_external_system_oauth/__init__.py b/base_external_system_oauth/__init__.py index 494cc90f0..75d792451 100644 --- a/base_external_system_oauth/__init__.py +++ b/base_external_system_oauth/__init__.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html). from . import models diff --git a/base_external_system_oauth/__manifest__.py b/base_external_system_oauth/__manifest__.py index d254a1010..ff35aa1c4 100644 --- a/base_external_system_oauth/__manifest__.py +++ b/base_external_system_oauth/__manifest__.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # Copyright 2023 Therp BV . # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). diff --git a/base_external_system_oauth/models/__init__.py b/base_external_system_oauth/models/__init__.py index 92ee85f41..2acf33911 100644 --- a/base_external_system_oauth/models/__init__.py +++ b/base_external_system_oauth/models/__init__.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from . import auth_oauth_provider diff --git a/base_external_system_oauth/models/auth_oauth_provider.py b/base_external_system_oauth/models/auth_oauth_provider.py index a6f57c72d..09749257a 100644 --- a/base_external_system_oauth/models/auth_oauth_provider.py +++ b/base_external_system_oauth/models/auth_oauth_provider.py @@ -10,7 +10,6 @@ from odoo import fields, models from odoo.exceptions import UserError - _logger = logging.getLogger(__name__) # pylint: disable=invalid-name diff --git a/base_external_system_oauth/models/external_system.py b/base_external_system_oauth/models/external_system.py index 941ecd465..b5569341d 100644 --- a/base_external_system_oauth/models/external_system.py +++ b/base_external_system_oauth/models/external_system.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # Copyright 2023 Therp BV . # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). diff --git a/base_external_system_oauth/models/external_system_adapter_oauth.py b/base_external_system_oauth/models/external_system_adapter_oauth.py index 4337bcc7a..26e46feac 100644 --- a/base_external_system_oauth/models/external_system_adapter_oauth.py +++ b/base_external_system_oauth/models/external_system_adapter_oauth.py @@ -1,11 +1,8 @@ -# -*- coding: utf-8 -*- # Copyright 2023 Therp BV. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). # pylint: disable=no-member """Extend external system with oauth authentication.""" -import json import logging -import requests from odoo import _, api, models from odoo.exceptions import UserError @@ -21,11 +18,7 @@ def strip_empty(data): """Strip all empty data from nested datastructure.""" if isinstance(data, dict): - return { - k: strip_empty(v) - for k, v in data.items() - if k and v - } + return {k: strip_empty(v) for k, v in data.items() if k and v} if isinstance(data, list): return [strip_empty(item) for item in data if item] if isinstance(data, tuple): @@ -75,16 +68,16 @@ def post(self, endpoint=None, data=None, json=None, **kwargs): """Send post request.""" headers = kwargs.pop("headers", {}) self._set_oauth_headers(headers) - return super( - ExternalSystemAdapterOAuth, self - ).post(endpoint=endpoint, data=data, json=json, headers=headers, **kwargs) + return super(ExternalSystemAdapterOAuth, self).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.""" self._set_oauth_headers(**kwargs) - return super( - ExternalSystemAdapterOAuth, self - ).get(endpoint=endpoint, params=params, **kwargs) + return super(ExternalSystemAdapterOAuth, self).get( + endpoint=endpoint, params=params, **kwargs + ) def _set_oauth_headers(self, headers): """Set headers in keyword arguments.""" @@ -102,5 +95,5 @@ def _add_authorization_header(self, headers): headers["Authorization"] = "Bearer %(token)s" % {"token": self.token} def strip_empty_data(self, data): - """"Utility method that can be called on adapter to cleanup data.""" + """ "Utility method that can be called on adapter to cleanup data.""" return strip_empty(data) 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..a687debd9 --- /dev/null +++ b/base_external_system_oauth/static/description/index.html @@ -0,0 +1,422 @@ + + + + + + +Base External System - oauth systems + + + +
+

Base External System - oauth systems

+ + +

Beta License: AGPL-3 OCA/server-tools 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.

+

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.

+
+
+
+ + From 4990595afff323dd11b4caa478e4e97a729571a6 Mon Sep 17 00:00:00 2001 From: Ronald Portier Date: Wed, 3 Apr 2024 15:54:44 +0200 Subject: [PATCH 03/14] [MIG] base_external_system_oath: migration to 16.0 --- base_external_system_oauth/README.rst | 38 +++++++++++-------- base_external_system_oauth/__init__.py | 2 +- base_external_system_oauth/__manifest__.py | 13 ++++--- .../models/auth_oauth_provider.py | 19 ++++++---- .../models/external_system_adapter_oauth.py | 13 ++----- .../readme/CONTRIBUTORS.md | 1 + .../readme/CONTRIBUTORS.rst | 1 - .../readme/DESCRIPTION.md | 2 + .../readme/DESCRIPTION.rst | 2 - .../static/description/index.html | 16 ++++---- 10 files changed, 59 insertions(+), 48 deletions(-) create mode 100644 base_external_system_oauth/readme/CONTRIBUTORS.md delete mode 100644 base_external_system_oauth/readme/CONTRIBUTORS.rst create mode 100644 base_external_system_oauth/readme/DESCRIPTION.md delete mode 100644 base_external_system_oauth/readme/DESCRIPTION.rst diff --git a/base_external_system_oauth/README.rst b/base_external_system_oauth/README.rst index 3f9fb2c45..b8c82f24b 100644 --- a/base_external_system_oauth/README.rst +++ b/base_external_system_oauth/README.rst @@ -7,7 +7,7 @@ Base External System - oauth systems !! This file is generated by oca-gen-addon-readme !! !! changes will be overwritten. !! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! - !! source digest: sha256:b7bcb98052072b585356539a42b3f52c0a030e9a943f1cb3ea63866911106c7e + !! source digest: sha256:77d7250a4605033a74e2d37e252c7ed0fe7f4b957ddabafc8437b671c4a9563b !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! .. |badge1| image:: https://img.shields.io/badge/maturity-Beta-yellow.png @@ -16,20 +16,20 @@ Base External System - oauth systems .. |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/16.0/base_external_system_oauth - :alt: OCA/server-tools +.. |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-tools-16-0/server-tools-16-0-base_external_system_oauth + :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-tools&target_branch=16.0 + :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. +This module adds the oauth authentication method to connect to remote +systems. **Table of contents** @@ -39,10 +39,10 @@ to remote systems. Bug Tracker =========== -Bugs are tracked on `GitHub Issues `_. +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 `_. +`feedback `_. Do not contact contributors directly about support or help with technical issues. @@ -50,17 +50,17 @@ Credits ======= Authors -~~~~~~~ +------- * Therp BV Contributors -~~~~~~~~~~~~ +------------ -* Ronald Portier +- Ronald Portier Maintainers -~~~~~~~~~~~ +----------- This module is maintained by the OCA. @@ -72,6 +72,14 @@ 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. +.. |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 index 75d792451..83e553ac4 100644 --- a/base_external_system_oauth/__init__.py +++ b/base_external_system_oauth/__init__.py @@ -1,3 +1,3 @@ -# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html). +# 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 index ff35aa1c4..94461d84f 100644 --- a/base_external_system_oauth/__manifest__.py +++ b/base_external_system_oauth/__manifest__.py @@ -1,16 +1,15 @@ -# Copyright 2023 Therp BV . +# 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 trough oauth authentication.", - "version": "10.0.1.0.0", + "summary": "Connect to external systems through oauth authentication.", + "version": "16.0.1.0.0", "category": "Base", - "website": "https://github.com/OCA/server-tools", + "website": "https://github.com/OCA/server-backend", "author": "Therp BV, Odoo Community Association (OCA)", + "maintainers": ["NL66278"], "license": "AGPL-3", - "application": False, - "installable": True, "depends": [ "auth_oauth", "base_external_system_http", @@ -19,4 +18,6 @@ "views/external_system.xml", "views/auth_oauth_provider.xml", ], + "application": False, + "installable": True, } diff --git a/base_external_system_oauth/models/auth_oauth_provider.py b/base_external_system_oauth/models/auth_oauth_provider.py index 09749257a..8dad755aa 100644 --- a/base_external_system_oauth/models/auth_oauth_provider.py +++ b/base_external_system_oauth/models/auth_oauth_provider.py @@ -7,7 +7,7 @@ import requests from requests.auth import HTTPBasicAuth -from odoo import fields, models +from odoo import _, fields, models from odoo.exceptions import UserError _logger = logging.getLogger(__name__) # pylint: disable=invalid-name @@ -46,7 +46,7 @@ def _get_access_token_basic(self): } basic = HTTPBasicAuth(self.client_id, self.client_secret) response = requests.post( - url=self.auth_endpoint, params=login_params, auth=basic + url=self.auth_endpoint, params=login_params, auth=basic, timeout=16 ) self._check_response(response) return response.json()["access_token"] @@ -68,7 +68,7 @@ def _get_access_token_microsoft_client_secret(self): } login_headers = {"Content-Type": "application/x-www-form-urlencoded"} response = requests.post( - url=login_url, headers=login_headers, data=login_params + url=login_url, headers=login_headers, data=login_params, timeout=16 ) self._check_response(response) return response.json()["access_token"] @@ -77,10 +77,15 @@ 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} + _( + "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", diff --git a/base_external_system_oauth/models/external_system_adapter_oauth.py b/base_external_system_oauth/models/external_system_adapter_oauth.py index 26e46feac..14888250e 100644 --- a/base_external_system_oauth/models/external_system_adapter_oauth.py +++ b/base_external_system_oauth/models/external_system_adapter_oauth.py @@ -4,7 +4,7 @@ """Extend external system with oauth authentication.""" import logging -from odoo import _, api, models +from odoo import _, models from odoo.exceptions import UserError # You must initialize logging, otherwise you'll not see debug output. @@ -44,15 +44,13 @@ class ExternalSystemAdapterOAuth(models.AbstractModel): token = None - @api.multi def external_get_client(self): """Return token that can be used to access remote system.""" - client = super(ExternalSystemAdapterOAuth, self).external_get_client() + client = super().external_get_client() oauth = self.system_id.oauth_definition_id self.token = oauth.get_access_token() return client - @api.multi def external_destroy_client(self, client): """Perform any logic necessary to destroy the client connection. @@ -62,22 +60,19 @@ def external_destroy_client(self, client): """ if self.token: self.token = None - super(ExternalSystemAdapterOAuth, self).external_destroy_client(client) def post(self, endpoint=None, data=None, json=None, **kwargs): """Send post request.""" headers = kwargs.pop("headers", {}) self._set_oauth_headers(headers) - return super(ExternalSystemAdapterOAuth, self).post( + 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.""" self._set_oauth_headers(**kwargs) - return super(ExternalSystemAdapterOAuth, self).get( - endpoint=endpoint, params=params, **kwargs - ) + return super().get(endpoint=endpoint, params=params, **kwargs) def _set_oauth_headers(self, headers): """Set headers in keyword arguments.""" 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/CONTRIBUTORS.rst b/base_external_system_oauth/readme/CONTRIBUTORS.rst deleted file mode 100644 index 4e07c28e1..000000000 --- a/base_external_system_oauth/readme/CONTRIBUTORS.rst +++ /dev/null @@ -1 +0,0 @@ -* 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/readme/DESCRIPTION.rst b/base_external_system_oauth/readme/DESCRIPTION.rst deleted file mode 100644 index 16723bd3a..000000000 --- a/base_external_system_oauth/readme/DESCRIPTION.rst +++ /dev/null @@ -1,2 +0,0 @@ -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 index a687debd9..cf9338d6e 100644 --- a/base_external_system_oauth/static/description/index.html +++ b/base_external_system_oauth/static/description/index.html @@ -367,11 +367,11 @@

Base External System - oauth systems

!! This file is generated by oca-gen-addon-readme !! !! changes will be overwritten. !! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! -!! source digest: sha256:b7bcb98052072b585356539a42b3f52c0a030e9a943f1cb3ea63866911106c7e +!! source digest: sha256:77d7250a4605033a74e2d37e252c7ed0fe7f4b957ddabafc8437b671c4a9563b !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! --> -

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

-

This module adds the oauth authentication method to connect -to remote 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

    @@ -386,10 +386,10 @@

    Base External System - oauth systems

Bug Tracker

-

Bugs are tracked on GitHub Issues. +

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.

+feedback.

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

@@ -413,7 +413,9 @@

Maintainers

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.

+

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.

From f884b6565e79a36268cc40fd43e358c87a4c3139 Mon Sep 17 00:00:00 2001 From: Ronald Portier Date: Thu, 4 Apr 2024 16:17:31 +0200 Subject: [PATCH 04/14] [IMP] *-system_oauth: provide tests --- base_external_system_oauth/README.rst | 2 +- base_external_system_oauth/__manifest__.py | 2 + .../demo/auth_oauth_provider_demo.xml | 21 ++++++++++ .../demo/external_system_demo.xml | 17 ++++++++ .../models/auth_oauth_provider.py | 7 ++++ .../models/external_system_adapter_oauth.py | 6 ++- .../static/description/index.html | 2 +- base_external_system_oauth/tests/__init__.py | 3 ++ .../tests/test_external_system.py | 42 +++++++++++++++++++ 9 files changed, 99 insertions(+), 3 deletions(-) create mode 100644 base_external_system_oauth/demo/auth_oauth_provider_demo.xml create mode 100644 base_external_system_oauth/demo/external_system_demo.xml create mode 100644 base_external_system_oauth/tests/__init__.py create mode 100644 base_external_system_oauth/tests/test_external_system.py diff --git a/base_external_system_oauth/README.rst b/base_external_system_oauth/README.rst index b8c82f24b..4a74cb1c5 100644 --- a/base_external_system_oauth/README.rst +++ b/base_external_system_oauth/README.rst @@ -7,7 +7,7 @@ Base External System - oauth systems !! This file is generated by oca-gen-addon-readme !! !! changes will be overwritten. !! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! - !! source digest: sha256:77d7250a4605033a74e2d37e252c7ed0fe7f4b957ddabafc8437b671c4a9563b + !! source digest: sha256:698f8077f5eedd2e8893d1a01b9dee77c62c30a45b74dddfd092ae16cd8312df !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! .. |badge1| image:: https://img.shields.io/badge/maturity-Beta-yellow.png diff --git a/base_external_system_oauth/__manifest__.py b/base_external_system_oauth/__manifest__.py index 94461d84f..751e2413e 100644 --- a/base_external_system_oauth/__manifest__.py +++ b/base_external_system_oauth/__manifest__.py @@ -15,6 +15,8 @@ "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", ], 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..a9e9303c9 --- /dev/null +++ b/base_external_system_oauth/demo/auth_oauth_provider_demo.xml @@ -0,0 +1,21 @@ + + + + + + + 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..080f214ac --- /dev/null +++ b/base_external_system_oauth/demo/external_system_demo.xml @@ -0,0 +1,17 @@ + + + + + + Example system access with oauth athorization + external.system.adapter.oauth + https + api.example.com + + + + + diff --git a/base_external_system_oauth/models/auth_oauth_provider.py b/base_external_system_oauth/models/auth_oauth_provider.py index 8dad755aa..adb98e620 100644 --- a/base_external_system_oauth/models/auth_oauth_provider.py +++ b/base_external_system_oauth/models/auth_oauth_provider.py @@ -22,6 +22,7 @@ class AuthOAuthProvider(models.Model): client_secret = fields.Char() provider_type = fields.Selection( selection=[ + ("demo", "Use client_id and client_secret, but return fixed result"), ("basic", "Use client_id and client_secret for basic Authentication"), ("microsoft_client_secret", "Microsoft Client Secret autehntication"), ], @@ -39,6 +40,12 @@ def get_access_token(self): 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 = { diff --git a/base_external_system_oauth/models/external_system_adapter_oauth.py b/base_external_system_oauth/models/external_system_adapter_oauth.py index 14888250e..8c8c0daba 100644 --- a/base_external_system_oauth/models/external_system_adapter_oauth.py +++ b/base_external_system_oauth/models/external_system_adapter_oauth.py @@ -38,11 +38,15 @@ def strip_empty_spaces(string): class ExternalSystemAdapterOAuth(models.AbstractModel): """This is an Interface implementing the OAuth module.""" + __slots__ = ["token"] + _name = "external.system.adapter.oauth" _inherit = "external.system.adapter.http" _description = "External System Adapter OAuth" - token = None + def __init__(self, name, bases, attrs): + """Declare previous_dir variable.""" + super().__init__(name, bases, attrs) def external_get_client(self): """Return token that can be used to access remote system.""" diff --git a/base_external_system_oauth/static/description/index.html b/base_external_system_oauth/static/description/index.html index cf9338d6e..9fdaf7b28 100644 --- a/base_external_system_oauth/static/description/index.html +++ b/base_external_system_oauth/static/description/index.html @@ -367,7 +367,7 @@

Base External System - oauth systems

!! This file is generated by oca-gen-addon-readme !! !! changes will be overwritten. !! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! -!! source digest: sha256:77d7250a4605033a74e2d37e252c7ed0fe7f4b957ddabafc8437b671c4a9563b +!! source digest: sha256:698f8077f5eedd2e8893d1a01b9dee77c62c30a45b74dddfd092ae16cd8312df !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! -->

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 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": ""}) From 5662a8caeb5495c96a2be811b0221e04d344b185 Mon Sep 17 00:00:00 2001 From: Ronald Portier Date: Tue, 14 May 2024 12:40:26 +0200 Subject: [PATCH 05/14] [ADD] base_external_system_ms_client_assertion: new module --- base_external_system_oauth/models/__init__.py | 3 +- .../models/external_system_adapter_oauth.py | 80 +++---------------- ...external_system_interaction_oauth_mixin.py | 45 +++++++++++ 3 files changed, 59 insertions(+), 69 deletions(-) create mode 100644 base_external_system_oauth/models/external_system_interaction_oauth_mixin.py diff --git a/base_external_system_oauth/models/__init__.py b/base_external_system_oauth/models/__init__.py index 2acf33911..069e95a20 100644 --- a/base_external_system_oauth/models/__init__.py +++ b/base_external_system_oauth/models/__init__.py @@ -2,4 +2,5 @@ from . import auth_oauth_provider from . import external_system -from . import external_system_adapter_oauth +from . import external_system_interaction_oauth_mixin +from . import external_system_adapter_oauth # uses mixin diff --git a/base_external_system_oauth/models/external_system_adapter_oauth.py b/base_external_system_oauth/models/external_system_adapter_oauth.py index 8c8c0daba..4aed5c82d 100644 --- a/base_external_system_oauth/models/external_system_adapter_oauth.py +++ b/base_external_system_oauth/models/external_system_adapter_oauth.py @@ -1,38 +1,8 @@ -# Copyright 2023 Therp BV. +# Copyright 2023-2024 Therp BV. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). -# pylint: disable=no-member """Extend external system with oauth authentication.""" -import logging -from odoo import _, models -from odoo.exceptions import UserError - -# You must initialize logging, otherwise you'll not see debug output. -logging.basicConfig() -logging.getLogger().setLevel(logging.DEBUG) -requests_log = logging.getLogger("requests.packages.urllib3") -requests_log.setLevel(logging.DEBUG) -requests_log.propagate = True - - -def strip_empty(data): - """Strip all empty data from nested datastructure.""" - if isinstance(data, dict): - return {k: strip_empty(v) for k, v in data.items() if k and v} - if isinstance(data, list): - return [strip_empty(item) for item in data if item] - if isinstance(data, tuple): - return tuple(strip_empty(item) for item in data if item) - if isinstance(data, set): - return {strip_empty(item) for item in data if item} - return strip_empty_spaces(data) - - -def strip_empty_spaces(string): - """Remove all whitespace from end of string like item.""" - if isinstance(string, str): - return string.strip() - return string +from odoo import models class ExternalSystemAdapterOAuth(models.AbstractModel): @@ -41,12 +11,11 @@ class ExternalSystemAdapterOAuth(models.AbstractModel): __slots__ = ["token"] _name = "external.system.adapter.oauth" - _inherit = "external.system.adapter.http" - _description = "External System Adapter OAuth" - - def __init__(self, name, bases, attrs): - """Declare previous_dir variable.""" - super().__init__(name, bases, attrs) + _inherit = [ + "external.system.adapter.http", + "external.system.interaction.oauth.mixin", + ] + _description = __doc__ def external_get_client(self): """Return token that can be used to access remote system.""" @@ -56,43 +25,18 @@ def external_get_client(self): return client def external_destroy_client(self, client): - """Perform any logic necessary to destroy the client connection. - - Args: - client (mixed): The client that was returned by - ``external_get_client``. - """ + """Perform any logic necessary to destroy the client connection.""" if self.token: self.token = None def post(self, endpoint=None, data=None, json=None, **kwargs): """Send post request.""" headers = kwargs.pop("headers", {}) - self._set_oauth_headers(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.""" - self._set_oauth_headers(**kwargs) - return super().get(endpoint=endpoint, params=params, **kwargs) - - def _set_oauth_headers(self, headers): - """Set headers in keyword arguments.""" - self._check_token() - headers["Content-Type"] = "application/json" - self._add_authorization_header(headers) - - def _check_token(self): - """Check for connection authorization (we have a token).""" - if not self.token: - raise UserError(_("Not connected to external system %s.") % self.name) - - def _add_authorization_header(self, headers): - """Add authorization header to the passed headers dictionary.""" - headers["Authorization"] = "Bearer %(token)s" % {"token": self.token} - - def strip_empty_data(self, data): - """ "Utility method that can be called on adapter to cleanup data.""" - return strip_empty(data) + 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..09140c4a6 --- /dev/null +++ b/base_external_system_oauth/models/external_system_interaction_oauth_mixin.py @@ -0,0 +1,45 @@ +# 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.""" + self._set_headers(**kwargs) + return super().get(endpoint=endpoint, params=params, **kwargs) + + 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"] = "Bearer %(token)s" % {"token": token} + + def _get_token(self): + """Need to override this with concrete implementation.""" + raise UserError(_("Methode _get_token needs concrete implementation")) From f7f334433f374340d45c52b12a39ca7866763aa7 Mon Sep 17 00:00:00 2001 From: Ronald Portier Date: Thu, 16 May 2024 17:53:13 +0200 Subject: [PATCH 06/14] [FIX] base_..._oauth: no need for basic type provider. Basic authentication is no oauth at all and fully handled by base_external_system_http. --- .../models/auth_oauth_provider.py | 21 ++++--------------- 1 file changed, 4 insertions(+), 17 deletions(-) diff --git a/base_external_system_oauth/models/auth_oauth_provider.py b/base_external_system_oauth/models/auth_oauth_provider.py index adb98e620..6e07610f1 100644 --- a/base_external_system_oauth/models/auth_oauth_provider.py +++ b/base_external_system_oauth/models/auth_oauth_provider.py @@ -1,4 +1,4 @@ -# Copyright 2020 Therp BV . +# 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.""" @@ -22,11 +22,10 @@ class AuthOAuthProvider(models.Model): client_secret = fields.Char() provider_type = fields.Selection( selection=[ - ("demo", "Use client_id and client_secret, but return fixed result"), - ("basic", "Use client_id and client_secret for basic Authentication"), - ("microsoft_client_secret", "Microsoft Client Secret autehntication"), + ("demo", "DEMO Just for testing purposes"), + ("microsoft_client_secret", "Microsoft Client Secret Authentication"), ], - default="basic", + default="demo", help="Provider type determines the method to retrieve bearer token", ) @@ -46,18 +45,6 @@ def _get_access_token_demo(self): 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, params=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 = "%(auth_endpoint)s/%(tenant_id)s%(validation_endpoint)s" % { From 1f64aadc2038ccc120b2300a18713a2f8c8edc1a Mon Sep 17 00:00:00 2001 From: ntsirintanis Date: Tue, 6 Aug 2024 12:32:18 +0200 Subject: [PATCH 07/14] [FIX] retrieve headers from kwargs --- .../models/external_system_interaction_oauth_mixin.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) 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 index 09140c4a6..2e2933688 100644 --- a/base_external_system_oauth/models/external_system_interaction_oauth_mixin.py +++ b/base_external_system_oauth/models/external_system_interaction_oauth_mixin.py @@ -23,7 +23,8 @@ def post(self, endpoint=None, data=None, json=None, **kwargs): def get_json(self, endpoint=None, params=None, **kwargs): """Get json formatted data from remote system.""" - self._set_headers(**kwargs) + headers = kwargs.get("headers", {}) + self._set_headers(headers) return super().get(endpoint=endpoint, params=params, **kwargs) def _set_headers(self, headers): From 49e4f2f64eb8b78e7f9a066756869b85da69054e Mon Sep 17 00:00:00 2001 From: Nikos Tsirintanis <38418585+ntsirintanis@users.noreply.github.com> Date: Wed, 18 Sep 2024 12:46:16 +0200 Subject: [PATCH 08/14] [FIX] base_external_system_oauth: add headers in kwargs --- .../models/external_system_interaction_oauth_mixin.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 index 2e2933688..1982da215 100644 --- a/base_external_system_oauth/models/external_system_interaction_oauth_mixin.py +++ b/base_external_system_oauth/models/external_system_interaction_oauth_mixin.py @@ -25,7 +25,7 @@ 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, **kwargs) + return super().get(endpoint=endpoint, params=params, **dict(kwargs, headers=headers)) def _set_headers(self, headers): """Set headers in keyword arguments.""" From 65284c9d8c3e7b954164879f8e1e6be5cf93e1ad Mon Sep 17 00:00:00 2001 From: Ronald Portier Date: Mon, 7 Oct 2024 10:11:26 +0200 Subject: [PATCH 09/14] [FIX] base_..._oauth: more pre-commit stuff --- base_external_system_oauth/models/auth_oauth_provider.py | 1 - .../models/external_system_interaction_oauth_mixin.py | 4 +++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/base_external_system_oauth/models/auth_oauth_provider.py b/base_external_system_oauth/models/auth_oauth_provider.py index 6e07610f1..617cf92af 100644 --- a/base_external_system_oauth/models/auth_oauth_provider.py +++ b/base_external_system_oauth/models/auth_oauth_provider.py @@ -5,7 +5,6 @@ import logging import requests -from requests.auth import HTTPBasicAuth from odoo import _, fields, models from odoo.exceptions import UserError 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 index 1982da215..793f35eb1 100644 --- a/base_external_system_oauth/models/external_system_interaction_oauth_mixin.py +++ b/base_external_system_oauth/models/external_system_interaction_oauth_mixin.py @@ -25,7 +25,9 @@ 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)) + return super().get( + endpoint=endpoint, params=params, **dict(kwargs, headers=headers) + ) def _set_headers(self, headers): """Set headers in keyword arguments.""" From ee58064583e89d6a88e1b86202f6936e1dc87994 Mon Sep 17 00:00:00 2001 From: Ronald Portier Date: Tue, 15 Oct 2024 17:40:01 +0200 Subject: [PATCH 10/14] [FIX] ..oauth: problem with setting token variable --- .../models/external_system_adapter_oauth.py | 23 +++++++++++++++---- 1 file changed, 18 insertions(+), 5 deletions(-) diff --git a/base_external_system_oauth/models/external_system_adapter_oauth.py b/base_external_system_oauth/models/external_system_adapter_oauth.py index 4aed5c82d..0c9a2bf2a 100644 --- a/base_external_system_oauth/models/external_system_adapter_oauth.py +++ b/base_external_system_oauth/models/external_system_adapter_oauth.py @@ -8,8 +8,6 @@ class ExternalSystemAdapterOAuth(models.AbstractModel): """This is an Interface implementing the OAuth module.""" - __slots__ = ["token"] - _name = "external.system.adapter.oauth" _inherit = [ "external.system.adapter.http", @@ -17,6 +15,21 @@ class ExternalSystemAdapterOAuth(models.AbstractModel): ] _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() @@ -25,9 +38,9 @@ def external_get_client(self): return client def external_destroy_client(self, client): - """Perform any logic necessary to destroy the client connection.""" - if self.token: - self.token = None + """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.""" From 8c2dc51d0eacb7ca09842653aa7ba20a154247ba Mon Sep 17 00:00:00 2001 From: Ronald Portier Date: Fri, 22 Nov 2024 00:59:31 +0100 Subject: [PATCH 11/14] [FIX] restore basic oauth connection --- .../models/auth_oauth_provider.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/base_external_system_oauth/models/auth_oauth_provider.py b/base_external_system_oauth/models/auth_oauth_provider.py index 617cf92af..da11ccfff 100644 --- a/base_external_system_oauth/models/auth_oauth_provider.py +++ b/base_external_system_oauth/models/auth_oauth_provider.py @@ -5,6 +5,7 @@ import logging import requests +from requests.auth import HTTPBasicAuth from odoo import _, fields, models from odoo.exceptions import UserError @@ -22,6 +23,7 @@ class AuthOAuthProvider(models.Model): 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", @@ -44,6 +46,18 @@ def _get_access_token_demo(self): 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, params=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 = "%(auth_endpoint)s/%(tenant_id)s%(validation_endpoint)s" % { From 68a402b287cc449f535026ef8e4ff5c03c5fafdd Mon Sep 17 00:00:00 2001 From: lfreeke Date: Tue, 20 Oct 2026 10:11:45 +0200 Subject: [PATCH 12/14] [IMP] base_external_system_oauth: pre-commit execution --- .../demo/auth_oauth_provider_demo.xml | 2 -- base_external_system_oauth/demo/external_system_demo.xml | 2 -- base_external_system_oauth/models/auth_oauth_provider.py | 7 ++----- .../models/external_system_interaction_oauth_mixin.py | 2 +- base_external_system_oauth/pyproject.toml | 3 +++ 5 files changed, 6 insertions(+), 10 deletions(-) create mode 100644 base_external_system_oauth/pyproject.toml diff --git a/base_external_system_oauth/demo/auth_oauth_provider_demo.xml b/base_external_system_oauth/demo/auth_oauth_provider_demo.xml index a9e9303c9..7f76bb5ee 100644 --- a/base_external_system_oauth/demo/auth_oauth_provider_demo.xml +++ b/base_external_system_oauth/demo/auth_oauth_provider_demo.xml @@ -4,7 +4,6 @@ License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). --> - Demo oauth providerI @@ -17,5 +16,4 @@ 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 index 080f214ac..933fb70f1 100644 --- a/base_external_system_oauth/demo/external_system_demo.xml +++ b/base_external_system_oauth/demo/external_system_demo.xml @@ -4,7 +4,6 @@ License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). --> - Example system access with oauth athorization external.system.adapter.oauth @@ -13,5 +12,4 @@ - diff --git a/base_external_system_oauth/models/auth_oauth_provider.py b/base_external_system_oauth/models/auth_oauth_provider.py index da11ccfff..c87b7ffa8 100644 --- a/base_external_system_oauth/models/auth_oauth_provider.py +++ b/base_external_system_oauth/models/auth_oauth_provider.py @@ -2,6 +2,7 @@ # 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 @@ -60,11 +61,7 @@ def _get_access_token_basic(self): def _get_access_token_microsoft_client_secret(self): """Get access token from Microsoft.""" - login_url = "%(auth_endpoint)s/%(tenant_id)s%(validation_endpoint)s" % { - "auth_endpoint": self.auth_endpoint, - "tenant_id": self.tenant_id, - "validation_endpoint": self.validation_endpoint, - } + 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, 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 index 793f35eb1..de5a9bf7f 100644 --- a/base_external_system_oauth/models/external_system_interaction_oauth_mixin.py +++ b/base_external_system_oauth/models/external_system_interaction_oauth_mixin.py @@ -41,7 +41,7 @@ def _add_authorization_header(self, headers): raise UserError( _("Not able to get bearer token for system %s.") % self.name ) - headers["Authorization"] = "Bearer %(token)s" % {"token": token} + headers["Authorization"] = f"Bearer {token}" def _get_token(self): """Need to override this with 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" From 68490a5e934bf3fd70e27293f9bec8c434066819 Mon Sep 17 00:00:00 2001 From: lfreeke Date: Tue, 20 Oct 2026 10:11:45 +0200 Subject: [PATCH 13/14] [MIG] base_external_system_oauth: Migration to 18.0 --- base_external_system_oauth/__manifest__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/base_external_system_oauth/__manifest__.py b/base_external_system_oauth/__manifest__.py index 751e2413e..26961ca8d 100644 --- a/base_external_system_oauth/__manifest__.py +++ b/base_external_system_oauth/__manifest__.py @@ -4,7 +4,7 @@ { "name": "Base External System - oauth systems", "summary": "Connect to external systems through oauth authentication.", - "version": "16.0.1.0.0", + "version": "18.0.1.0.0", "category": "Base", "website": "https://github.com/OCA/server-backend", "author": "Therp BV, Odoo Community Association (OCA)", From a8c4bfd423f8713e58a0ef2ed44047978cd42899 Mon Sep 17 00:00:00 2001 From: lfreeke Date: Mon, 14 Sep 2026 13:05:21 +0200 Subject: [PATCH 14/14] [FIX] login_params should be data --- base_external_system_oauth/models/auth_oauth_provider.py | 2 +- base_external_system_oauth/views/auth_oauth_provider.xml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/base_external_system_oauth/models/auth_oauth_provider.py b/base_external_system_oauth/models/auth_oauth_provider.py index c87b7ffa8..829ceb1ee 100644 --- a/base_external_system_oauth/models/auth_oauth_provider.py +++ b/base_external_system_oauth/models/auth_oauth_provider.py @@ -54,7 +54,7 @@ def _get_access_token_basic(self): } basic = HTTPBasicAuth(self.client_id, self.client_secret) response = requests.post( - url=self.auth_endpoint, params=login_params, auth=basic, timeout=16 + url=self.auth_endpoint, data=login_params, auth=basic, timeout=16 ) self._check_response(response) return response.json()["access_token"] diff --git a/base_external_system_oauth/views/auth_oauth_provider.xml b/base_external_system_oauth/views/auth_oauth_provider.xml index 17fff039a..5899c1de3 100644 --- a/base_external_system_oauth/views/auth_oauth_provider.xml +++ b/base_external_system_oauth/views/auth_oauth_provider.xml @@ -16,7 +16,7 @@ - +