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
106 changes: 106 additions & 0 deletions auth_api_key_hash/README.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
===================
Auth Api Key (Hash)
===================

.. !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!! This file is generated by oca-gen-addon-readme !!
!! changes will be overwritten. !!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

.. |badge1| image:: https://img.shields.io/badge/maturity-Beta-yellow.png
:target: https://odoo-community.org/page/development-status
:alt: Beta
.. |badge2| image:: https://img.shields.io/badge/licence-LGPL--3-blue.png
:target: http://www.gnu.org/licenses/lgpl-3.0-standalone.html
:alt: License: LGPL-3
.. |badge3| image:: https://img.shields.io/badge/github-OCA%2Fserver--auth-lightgray.png?logo=github
:target: https://github.com/OCA/server-auth/tree/13.0/auth_api_key_hash
:alt: OCA/server-auth
.. |badge4| image:: https://img.shields.io/badge/weblate-Translate%20me-F47D42.png
:target: https://translation.odoo-community.org/projects/server-auth-13-0/server-auth-13-0-auth_api_key_hash
:alt: Translate me on Weblate
.. |badge5| image:: https://img.shields.io/badge/runbot-Try%20me-875A7B.png
:target: https://runbot.odoo-community.org/runbot/251/13.0
:alt: Try me on Runbot

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

Authenticate http requests from an API key.

API keys are codes passed in (in the http header API-KEY) by programs calling an API in order to identify -in this case- the calling program's user.

Take care while using this kind of mechanism since information into http headers are visible in clear. Thus, use it only to authenticate requests from known sources. For unknown sources, it is a good practice to filter out this header at proxy level.

**Table of contents**

.. contents::
:local:

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

The api key menu is available into Settings > Technical in debug mode.
By default, when you create an API key, the key is saved into the database.
It is also possible to provide the value of this key via the configuration
file. This can be very useful to avoid mixing your keys between your various
environments when restoring databases. All you have to do is to add a new
section to your configuration file according to the following convention:

.. code-block:: ini

[api_key_<Record Name>]
key=my_api_key

Usage
=====

To apply this authentication system to your http request you must set 'api_key'
as value for the 'auth' parameter of your route definition into your controller.

.. code-block:: python

class MyController(Controller):

@route('/my_service', auth='api_key', ...)
def my_service(self, *args, **kwargs):
pass

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

Bugs are tracked on `GitHub Issues <https://github.com/OCA/server-auth/issues>`_.
In case of trouble, please check there if your issue has already been reported.
If you spotted it first, help us smashing it by providing a detailed and welcomed
`feedback <https://github.com/OCA/server-auth/issues/new?body=module:%20auth_api_key_hash%0Aversion:%2013.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
~~~~~~~

* Solvti Sp. z o.o.

Contributors
~~~~~~~~~~~~

* Stefan Wiselka <stefan.wiselka@solvti.pl>

Maintainers
~~~~~~~~~~~

This module is maintained by the OCA.

.. image:: https://odoo-community.org/logo.png
:alt: Odoo Community Association
:target: https://odoo-community.org

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

This module is part of the `OCA/server-auth <https://github.com/OCA/server-auth/tree/13.0/auth_api_key_hash>`_ project on GitHub.

You are welcome to contribute. To learn how please visit https://odoo-community.org/page/Contribute.
1 change: 1 addition & 0 deletions auth_api_key_hash/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
from . import models
15 changes: 15 additions & 0 deletions auth_api_key_hash/__manifest__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# Copyright 2023 Solvti Sp. z o.o.
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl).

{
"name": "Auth Api Key (Hash)",
"summary": """
Authenticate http requests from an API key (hash)""",
"version": "13.0.1.0.0",
"license": "LGPL-3",
"author": "Solvti Sp. z o.o.,Odoo Community Association (OCA)",
"website": "https://github.com/OCA/server-auth",
"depends": ["base", "base_sparse_field"],
"data": ["security/ir.model.access.csv", "views/auth_api_key_hash.xml"],
"demo": [],
}
110 changes: 110 additions & 0 deletions auth_api_key_hash/i18n/auth_api_key.pot
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
# Translation of Odoo Server.
# This file contains the translation of the following modules:
# * auth_api_key_hash
#
msgid ""
msgstr ""
"Project-Id-Version: Odoo Server 13.0\n"
"Report-Msgid-Bugs-To: \n"
"Last-Translator: \n"
"Language-Team: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: \n"
"Plural-Forms: \n"

#. module: auth_api_key_hash
#: model:ir.model,name:auth_api_key_hash.model_auth_api_key_hash
msgid "API Key (Hash)"
msgstr ""

#. module: auth_api_key_hash
#: model:ir.model.constraint,message:auth_api_key_hash.constraint_auth_api_key_hash_name_uniq
msgid "Api Key name must be unique."
msgstr ""

#. module: auth_api_key_hash
#: model:ir.actions.act_window,name:auth_api_key_hash.auth_api_key_hash_act_window
#: model:ir.ui.menu,name:auth_api_key_hash.auth_api_key_hash_menu
msgid "Auth Api Key (Hash)"
msgstr ""

#. module: auth_api_key_hash
#: model:ir.model.fields,field_description:auth_api_key_hash.field_auth_api_key_hash__create_uid
msgid "Created by"
msgstr ""

#. module: auth_api_key_hash
#: model:ir.model.fields,field_description:auth_api_key_hash.field_auth_api_key_hash__create_date
msgid "Created on"
msgstr ""

#. module: auth_api_key_hash
#: model:ir.model.fields,field_description:auth_api_key_hash.field_auth_api_key_hash__display_name
msgid "Display Name"
msgstr ""

#. module: auth_api_key_hash
#: model:ir.model,name:auth_api_key_hash.model_ir_http
msgid "HTTP Routing"
msgstr ""

#. module: auth_api_key_hash
#: model:ir.model.fields,field_description:auth_api_key_hash.field_auth_api_key_hash__id
msgid "ID"
msgstr ""

#. module: auth_api_key_hash
#: model:ir.model.fields,field_description:auth_api_key_hash.field_auth_api_key_hash__key
msgid "Key"
msgstr ""

#. module: auth_api_key_hash
#: model:ir.model.fields,field_description:auth_api_key_hash.field_auth_api_key_hash____last_update
msgid "Last Modified on"
msgstr ""

#. module: auth_api_key_hash
#: model:ir.model.fields,field_description:auth_api_key_hash.field_auth_api_key_hash__write_uid
msgid "Last Updated by"
msgstr ""

#. module: auth_api_key_hash
#: model:ir.model.fields,field_description:auth_api_key_hash.field_auth_api_key_hash__write_date
msgid "Last Updated on"
msgstr ""

#. module: auth_api_key_hash
#: model:ir.model.fields,field_description:auth_api_key_hash.field_auth_api_key_hash__name
msgid "Name"
msgstr ""

#. module: auth_api_key_hash
#: model:ir.model.fields,help:auth_api_key_hash.field_auth_api_key_hash__key
msgid ""
"The API key"
msgstr ""

#. module: auth_api_key_hash
#: code:addons/auth_api_key_hash/models/auth_api_key_hash.py:0
#, python-format
msgid "The key %s is not allowed"
msgstr ""

#. module: auth_api_key_hash
#: model:ir.model.fields,help:auth_api_key_hash.field_auth_api_key_hash__user_id
msgid ""
"The user used to process the requests authenticated by\n"
" the api key"
msgstr ""

#. module: auth_api_key_hash
#: model:ir.model.fields,field_description:auth_api_key_hash.field_auth_api_key_hash__user_id
msgid "User"
msgstr ""

#. module: auth_api_key_hash
#: code:addons/auth_api_key_hash/models/auth_api_key_hash.py:0
#, python-format
msgid "User is not allowed"
msgstr ""
2 changes: 2 additions & 0 deletions auth_api_key_hash/models/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
from . import ir_http
from . import auth_api_key_hash
69 changes: 69 additions & 0 deletions auth_api_key_hash/models/auth_api_key_hash.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
# Copyright 2023 Solvti Sp. z o.o.
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl).

from hashlib import md5

from odoo import _, api, fields, models, tools
from odoo.exceptions import AccessError, ValidationError
from odoo.tools import consteq


class AuthApiKeyHash(models.Model):
_name = "auth.api.key.hash"
_description = "API Key (Hash)"

name = fields.Char(required=True)
key = fields.Char(required=True, copy=False, help="""The API key.""",)
user_id = fields.Many2one(
comodel_name="res.users",
string="User",
required=True,
help="""The user used to process the requests authenticated by
the api key""",
)

_sql_constraints = [
("name_uniq", "unique(name)", "Api Key name must be unique."),
("key_uniq", "unique(key)", "Api Key must be unique."),
]

@api.model
def _retrieve_api_key(self, key):
return self.browse(self._retrieve_api_key_id(key))

@api.model
@tools.ormcache("key")
def _retrieve_api_key_id(self, key):
if not self.env.user.has_group("base.group_system"):
raise AccessError(_("User is not allowed"))
hash_key = md5(key.encode("utf-8")).hexdigest()
for api_key in self.search([]):
if consteq(hash_key, api_key.key):
Comment thread
MarcinSokolowski-Solvti marked this conversation as resolved.
return api_key.id
raise ValidationError(_("The key %s is not allowed") % key)

@api.model
@tools.ormcache("key")
def _retrieve_uid_from_api_key(self, key):
return self._retrieve_api_key(key).user_id.id

def _clear_key_cache(self):
self._retrieve_api_key_id.clear_cache(self.env[self._name])
self._retrieve_uid_from_api_key.clear_cache(self.env[self._name])

@api.model
def create(self, vals):
if new_key := vals.get("key", ""):
vals["key"] = md5(new_key.encode("utf-8")).hexdigest()
record = super(AuthApiKeyHash, self).create(vals)
if "key" in vals or "user_id" in vals:
self._clear_key_cache()
return record

def write(self, vals):
if vals.get("key", False):
raise ValidationError(_("You can't change api-key! Please add new one."))
super(AuthApiKeyHash, self).write(vals)
if "key" in vals or "user_id" in vals:
self._clear_key_cache()
return True
38 changes: 38 additions & 0 deletions auth_api_key_hash/models/ir_http.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
# Copyright 2023 Solvti Sp. z o.o.
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl).

import logging

from odoo import models
from odoo.exceptions import AccessDenied
from odoo.http import request

_logger = logging.getLogger(__name__)


class IrHttp(models.AbstractModel):
_inherit = "ir.http"

@classmethod
def _auth_method_api_key_hash(cls):
headers = request.httprequest.environ
api_key = headers.get("HTTP_API_KEY")
if api_key:
request.uid = 1
auth_api_key_hash = request.env["auth.api.key.hash"]._retrieve_api_key(
api_key
)
if auth_api_key_hash:
metadata = f"IP: {headers.get('REMOTE_ADDR')} USER_AGENT: {headers.get('HTTP_USER_AGENT')}, REFERER: {headers.get('HTTP_REFERER')}, ORIGIN: {headers.get('HTTP_ORIGIN')}"
_logger.info("api_key_hash called: Metadata -> {}".format(metadata))
# reset _env on the request since we change the uid...
# the next call to env will instantiate an new
# odoo.api.Environment with the user defined on the
# auth.api_key
request._env = None
request.uid = auth_api_key_hash.user_id.id
request.auth_api_key_hash = api_key
request.auth_api_key_hash_id = auth_api_key_hash.id
return True
_logger.error("Wrong HTTP_API_KEY, access denied")
raise AccessDenied()
2 changes: 2 additions & 0 deletions auth_api_key_hash/readme/CONFIGURE.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
The api key hash menu is available into Settings > Technical in debug mode.
By default, when you create an API key, the key is saved into the database as hash.
1 change: 1 addition & 0 deletions auth_api_key_hash/readme/CONTRIBUTORS.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* Stefan Wiselka <stefan.wiselka@solvti.pl>
5 changes: 5 additions & 0 deletions auth_api_key_hash/readme/DESCRIPTION.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
Authenticate http requests from an API key.

API keys are codes passed in (in the http header API-KEY) by programs calling an API in order to identify -in this case- the calling program's user.

Take care while using this kind of mechanism since information into http headers are visible in clear. Thus, use it only to authenticate requests from known sources. For unknown sources, it is a good practice to filter out this header at proxy level.
10 changes: 10 additions & 0 deletions auth_api_key_hash/readme/USAGE.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
To apply this authentication system to your http request you must set 'api_key_hash'
as value for the 'auth' parameter of your route definition into your controller.

.. code-block:: python

class MyController(Controller):

@route('/my_service', auth='api_key_hash', ...)
def my_service(self, *args, **kwargs):
pass
2 changes: 2 additions & 0 deletions auth_api_key_hash/security/ir.model.access.csv
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
id,name,model_id:id,group_id:id,perm_read,perm_write,perm_create,perm_unlink
access_auth_api_key_hash,access_auth_api_key_hash,model_auth_api_key_hash,base.group_system,1,1,1,1
Binary file added auth_api_key_hash/static/description/icon.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading