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
85 changes: 85 additions & 0 deletions base_external_system_oauth/README.rst
Original file line number Diff line number Diff line change
@@ -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 <https://github.com/OCA/server-backend/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-backend/issues/new?body=module:%20base_external_system_oauth%0Aversion:%2016.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
-------

* Therp BV

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

- Ronald Portier <ronald@therp.nl>

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 <https://odoo-community.org/page/maintainer-role>`__:

|maintainer-NL66278|

This module is part of the `OCA/server-backend <https://github.com/OCA/server-backend/tree/16.0/base_external_system_oauth>`_ project on GitHub.

You are welcome to contribute. To learn how please visit https://odoo-community.org/page/Contribute.
3 changes: 3 additions & 0 deletions base_external_system_oauth/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).

from . import models
25 changes: 25 additions & 0 deletions base_external_system_oauth/__manifest__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# Copyright 2023-2024 Therp BV <https://therp.nl>.
# 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,
}
19 changes: 19 additions & 0 deletions base_external_system_oauth/demo/auth_oauth_provider_demo.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<?xml version="1.0" encoding="utf-8" ?>
<!--
Copyright 2024 Therp BV.
License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
-->
<odoo noupdate="1">
<!-- Full url will be auth_endpoint/tenant_id/validation_endpoint. -->
<record id="oauth_provider_demo" model="auth.oauth.provider">
<field name="name">Demo oauth providerI</field>
<field name="auth_endpoint">https://api.example.com/oauth2/api/v1/token</field>
<field name="validation_endpoint">x</field>
<field name="provider_type">demo</field>
<field name="client_id">api_example_com</field>
<field name="client_secret">Set client secret to value from provider</field>
<field name="css_class">zocial</field>
<field name="body">Log in to oauth token provider</field>
<field name="enabled" eval="False" />
</record>
</odoo>
15 changes: 15 additions & 0 deletions base_external_system_oauth/demo/external_system_demo.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="utf-8" ?>
<!--
Copyright 2024 Therp BV.
License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
-->
<odoo>
<record id="external_system_oauth_demo" model="external.system">
<field name="name">Example system access with oauth athorization</field>
<field name="system_type">external.system.adapter.oauth</field>
<field name="scheme">https</field>
<field name="host">api.example.com</field>
<field name="oauth_definition_id" ref="oauth_provider_demo" />
<field name="company_ids" eval="[(5, 0), (4, ref('base.main_company'))]" />
</record>
</odoo>
6 changes: 6 additions & 0 deletions base_external_system_oauth/models/__init__.py
Original file line number Diff line number Diff line change
@@ -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
98 changes: 98 additions & 0 deletions base_external_system_oauth/models/auth_oauth_provider.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
# Copyright 2020-2024 Therp BV <https://therp.nl>.
# 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,
)
15 changes: 15 additions & 0 deletions base_external_system_oauth/models/external_system.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# Copyright 2023 Therp BV <https://therp.nl>.
# 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",
)
55 changes: 55 additions & 0 deletions base_external_system_oauth/models/external_system_adapter_oauth.py
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
@@ -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"))
3 changes: 3 additions & 0 deletions base_external_system_oauth/pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
[build-system]
requires = ["whool"]
build-backend = "whool.buildapi"
1 change: 1 addition & 0 deletions base_external_system_oauth/readme/CONTRIBUTORS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
- Ronald Portier \<<ronald@therp.nl>\>
2 changes: 2 additions & 0 deletions base_external_system_oauth/readme/DESCRIPTION.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
This module adds the oauth authentication method to connect to remote
systems.
Loading
Loading