Skip to content

Commit

Permalink
[IMP] fastapi_auth_jwt: pre-commit auto fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
antonyht27 committed Oct 1, 2024
1 parent 0e3d90d commit 6d78969
Show file tree
Hide file tree
Showing 10 changed files with 176 additions and 150 deletions.
1 change: 0 additions & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ exclude: |
^datamodel/|
^extendable/|
^extendable_fastapi/|
^fastapi_auth_jwt/|
^fastapi_auth_jwt_demo/|
^graphql_base/|
^graphql_demo/|
Expand Down
78 changes: 43 additions & 35 deletions fastapi_auth_jwt/README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -20,16 +20,17 @@ FastAPI Auth JWT support
:target: https://github.com/OCA/rest-framework/tree/17.0/fastapi_auth_jwt
:alt: OCA/rest-framework
.. |badge4| image:: https://img.shields.io/badge/weblate-Translate%20me-F47D42.png
:target: https://translation.odoo-community.org/projects/rest-framework-16-0/rest-framework-16-0-fastapi_auth_jwt
:target: https://translation.odoo-community.org/projects/rest-framework-17-0/rest-framework-17-0-fastapi_auth_jwt
: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/rest-framework&target_branch=17.0
:alt: Try me on Runboat

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

This module provides ``FastAPI`` ``Depends`` to allow authentication with `auth_jwt
<https://github.com/OCA/server-auth/tree/17.0/auth_jwt>`_.
This module provides ``FastAPI`` ``Depends`` to allow authentication
with
`auth_jwt <https://github.com/OCA/server-auth/tree/16.0/auth_jwt>`__.

**Table of contents**

Expand All @@ -39,62 +40,69 @@ This module provides ``FastAPI`` ``Depends`` to allow authentication with `auth_
Usage
=====

The following FastAPI dependencies are provided and importable from
The following FastAPI dependencies are provided and importable from
``odoo.addons.fastapi_auth_jwt.dependencies``:

``def auth_jwt_authenticated_payload() -> Payload``

Return the authenticated JWT payload. Raise a 401 (unauthorized) if absent or invalid.
Return the authenticated JWT payload. Raise a 401 (unauthorized) if
absent or invalid.

``def auth_jwt_optionally_authenticated_payload() -> Payload | None``

Return the authenticated JWT payload, or ``None`` if the ``Authorization`` header and
cookie are absent. Raise a 401 (unauthorized) if present and invalid.
Return the authenticated JWT payload, or ``None`` if the
``Authorization`` header and cookie are absent. Raise a 401
(unauthorized) if present and invalid.

``def auth_jwt_authenticated_partner() -> Partner``

Obtain the authenticated partner corresponding to the provided JWT token, according to
the partner strategy defined on the ``auth_jwt`` validator. Raise a 401 (unauthorized)
if the partner could not be determined for any reason.
Obtain the authenticated partner corresponding to the provided JWT
token, according to the partner strategy defined on the ``auth_jwt``
validator. Raise a 401 (unauthorized) if the partner could not be
determined for any reason.

This is function suitable and intended to override
``odoo.addons.fastapi.dependencies.authenticated_partner_impl``.
This is function suitable and intended to override
``odoo.addons.fastapi.dependencies.authenticated_partner_impl``.

The partner record returned by this function is bound to an environment that uses the
Odoo user obtained from the user strategy defined on the ``auth_jwt`` validator. When
used ``authenticated_partner_impl`` this in turn ensures that
``odoo.addons.fastapi.dependencies.authenticated_partner_env`` is also bound to the
correct Odoo user.
The partner record returned by this function is bound to an
environment that uses the Odoo user obtained from the user strategy
defined on the ``auth_jwt`` validator. When used
``authenticated_partner_impl`` this in turn ensures that
``odoo.addons.fastapi.dependencies.authenticated_partner_env`` is
also bound to the correct Odoo user.

``def auth_jwt_optionally_authenticated_partner() -> Partner``

Same as ``auth_jwt_partner`` except it returns an empty recordset bound to the
``public`` user if the ``Authorization`` header and cookie are absent, or if the JWT
validator could not find the partner and declares that the partner is not required.
Same as ``auth_jwt_partner`` except it returns an empty recordset
bound to the ``public`` user if the ``Authorization`` header and
cookie are absent, or if the JWT validator could not find the partner
and declares that the partner is not required.

``def auth_jwt_authenticated_odoo_env() -> Environment``

Return an Odoo environment using the the Odoo user obtained from the user strategy
defined on the ``auth_jwt`` validator, if the request could be authenticated using a
JWT validator. Raise a 401 (unauthorized) otherwise.
Return an Odoo environment using the the Odoo user obtained from the
user strategy defined on the ``auth_jwt`` validator, if the request
could be authenticated using a JWT validator. Raise a 401
(unauthorized) otherwise.

This is function suitable and intended to override
``odoo.addons.fastapi.dependencies.authenticated_odoo_env_impl``.
This is function suitable and intended to override
``odoo.addons.fastapi.dependencies.authenticated_odoo_env_impl``.

``def auth_jwt_default_validator_name() -> str | None``

Return the name of the default JWT validator to use.
Return the name of the default JWT validator to use.

The default implementation returns ``None`` meaning only one active JWT validator is
allowed. This dependency is meant to be overridden.
The default implementation returns ``None`` meaning only one active
JWT validator is allowed. This dependency is meant to be overridden.

``def auth_jwt_http_header_authorization() -> str | None``

By default, return the credentials part of the ``Authorization`` header, or ``None``
if absent. This dependency is meant to be overridden, in particular with
``fastapi.security.OAuth2AuthorizationCodeBearer`` to let swagger handle OAuth2
authorization (such override is only necessary for comfort when using the swagger
interface).
By default, return the credentials part of the ``Authorization``
header, or ``None`` if absent. This dependency is meant to be
overridden, in particular with
``fastapi.security.OAuth2AuthorizationCodeBearer`` to let swagger
handle OAuth2 authorization (such override is only necessary for
comfort when using the swagger interface).

Bug Tracker
===========
Expand All @@ -110,12 +118,12 @@ Credits
=======

Authors
~~~~~~~
-------

* ACSONE SA/NV

Maintainers
~~~~~~~~~~~
-----------

This module is maintained by the OCA.

Expand Down
41 changes: 20 additions & 21 deletions fastapi_auth_jwt/dependencies.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl).

import logging
from typing import Annotated, Any, Dict, Optional, Tuple, Union
from typing import Annotated, Any

from starlette.status import HTTP_401_UNAUTHORIZED

Expand All @@ -24,12 +24,11 @@

_logger = logging.getLogger(__name__)


Payload = Dict[str, Any]
Payload = dict[str, Any]


def _get_auth_jwt_validator(
validator_name: Union[str, None],
validator_name: str | None,
env: Environment,
) -> AuthJwtValidator:
validator = env["auth.jwt.validator"].sudo()._get_validator_by_name(validator_name)
Expand All @@ -39,9 +38,9 @@ def _get_auth_jwt_validator(

def _request_has_authentication(
request: Request,
authorization_header: Optional[str],
authorization_header: str | None,
validator: AuthJwtValidator,
) -> Union[Payload, None]:
) -> Payload | None:
if authorization_header is not None:
return True
if not validator.cookie_enabled:
Expand All @@ -52,7 +51,7 @@ def _request_has_authentication(

def _get_jwt_payload(
request: Request,
authorization_header: Optional[str],
authorization_header: str | None,
validator: AuthJwtValidator,
) -> Payload:
"""Obtain and validate the JWT payload from the request authorization header or
Expand All @@ -76,9 +75,9 @@ def _get_jwt_payload(
def _get_jwt_payload_and_validator(
request: Request,
response: Response,
authorization_header: Optional[str],
authorization_header: str | None,
validator: AuthJwtValidator,
) -> Tuple[Payload, AuthJwtValidator]:
) -> tuple[Payload, AuthJwtValidator]:
try:
payload = None
exceptions = {}
Expand Down Expand Up @@ -117,24 +116,24 @@ def _get_jwt_payload_and_validator(
raise HTTPException(status_code=HTTP_401_UNAUTHORIZED) from e


def auth_jwt_default_validator_name() -> Union[str, None]:
def auth_jwt_default_validator_name() -> str | None:
return None


def auth_jwt_http_header_authorization(
credentials: Annotated[
Optional[HTTPAuthorizationCredentials],
HTTPAuthorizationCredentials | None,
Depends(HTTPBearer(auto_error=False)),
]
):
],
) -> str | None:
if credentials is None:
return None
return credentials.credentials


class BaseAuthJwt: # noqa: B903
def __init__(
self, validator_name: Optional[str] = None, allow_unauthenticated: bool = False
self, validator_name: str | None = None, allow_unauthenticated: bool = False
):
self.validator_name = validator_name
self.allow_unauthenticated = allow_unauthenticated
Expand All @@ -146,18 +145,18 @@ def __call__(
request: Request,
response: Response,
authorization_header: Annotated[
Optional[str],
str | None,
Depends(auth_jwt_http_header_authorization),
],
default_validator_name: Annotated[
Union[str, None],
str | None,
Depends(auth_jwt_default_validator_name),
],
env: Annotated[
Environment,
Depends(odoo_env),
],
) -> Optional[Payload]:
) -> Payload | None:
validator = _get_auth_jwt_validator(
self.validator_name or default_validator_name, env
)
Expand All @@ -176,11 +175,11 @@ def __call__(
request: Request,
response: Response,
authorization_header: Annotated[
Optional[str],
str | None,
Depends(auth_jwt_http_header_authorization),
],
default_validator_name: Annotated[
Union[str, None],
str | None,
Depends(auth_jwt_default_validator_name),
],
env: Annotated[
Expand Down Expand Up @@ -215,11 +214,11 @@ def __call__(
request: Request,
response: Response,
authorization_header: Annotated[
Optional[str],
str | None,
Depends(auth_jwt_http_header_authorization),
],
default_validator_name: Annotated[
Union[str, None],
str | None,
Depends(auth_jwt_default_validator_name),
],
env: Annotated[
Expand Down
3 changes: 3 additions & 0 deletions fastapi_auth_jwt/pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
[build-system]
requires = ["whool"]
build-backend = "whool.buildapi"
2 changes: 2 additions & 0 deletions fastapi_auth_jwt/readme/DESCRIPTION.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
This module provides `FastAPI` `Depends` to allow authentication with
[auth_jwt](https://github.com/OCA/server-auth/tree/16.0/auth_jwt).
2 changes: 0 additions & 2 deletions fastapi_auth_jwt/readme/DESCRIPTION.rst

This file was deleted.

62 changes: 62 additions & 0 deletions fastapi_auth_jwt/readme/USAGE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
The following FastAPI dependencies are provided and importable from
`odoo.addons.fastapi_auth_jwt.dependencies`:

`def auth_jwt_authenticated_payload() -> Payload`

> Return the authenticated JWT payload. Raise a 401 (unauthorized) if
> absent or invalid.
`def auth_jwt_optionally_authenticated_payload() -> Payload | None`

> Return the authenticated JWT payload, or `None` if the `Authorization`
> header and cookie are absent. Raise a 401 (unauthorized) if present
> and invalid.
`def auth_jwt_authenticated_partner() -> Partner`

> Obtain the authenticated partner corresponding to the provided JWT
> token, according to the partner strategy defined on the `auth_jwt`
> validator. Raise a 401 (unauthorized) if the partner could not be
> determined for any reason.
>
> This is function suitable and intended to override
> `odoo.addons.fastapi.dependencies.authenticated_partner_impl`.
>
> The partner record returned by this function is bound to an
> environment that uses the Odoo user obtained from the user strategy
> defined on the `auth_jwt` validator. When used
> `authenticated_partner_impl` this in turn ensures that
> `odoo.addons.fastapi.dependencies.authenticated_partner_env` is also
> bound to the correct Odoo user.
`def auth_jwt_optionally_authenticated_partner() -> Partner`

> Same as `auth_jwt_partner` except it returns an empty recordset bound
> to the `public` user if the `Authorization` header and cookie are
> absent, or if the JWT validator could not find the partner and
> declares that the partner is not required.
`def auth_jwt_authenticated_odoo_env() -> Environment`

> Return an Odoo environment using the the Odoo user obtained from the
> user strategy defined on the `auth_jwt` validator, if the request
> could be authenticated using a JWT validator. Raise a 401
> (unauthorized) otherwise.
>
> This is function suitable and intended to override
> `odoo.addons.fastapi.dependencies.authenticated_odoo_env_impl`.
`def auth_jwt_default_validator_name() -> str | None`

> Return the name of the default JWT validator to use.
>
> The default implementation returns `None` meaning only one active JWT
> validator is allowed. This dependency is meant to be overridden.
`def auth_jwt_http_header_authorization() -> str | None`

> By default, return the credentials part of the `Authorization` header,
> or `None` if absent. This dependency is meant to be overridden, in
> particular with `fastapi.security.OAuth2AuthorizationCodeBearer` to
> let swagger handle OAuth2 authorization (such override is only
> necessary for comfort when using the swagger interface).
Loading

0 comments on commit 6d78969

Please sign in to comment.