| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
from django.http import HttpRequest |
| 4 |
|
| 5 |
from ninja.errors import HttpError |
| 6 |
from ninja.security.base import AuthBase |
| 7 |
|
| 8 |
from allauth.idp.oidc.internal.oauthlib.server import get_server |
| 9 |
from allauth.idp.oidc.internal.oauthlib.utils import ( |
| 10 |
extract_params, |
| 11 |
get_validator_context, |
| 12 |
) |
| 13 |
from allauth.idp.oidc.internal.resources import is_resources_subset |
| 14 |
from allauth.idp.oidc.internal.scope import is_scope_granted |
| 15 |
|
| 16 |
|
| 17 |
class TokenAuth(AuthBase): |
| 18 |
""" |
| 19 |
Use the OIDC access token to authenticate and the scopes attached to the |
| 20 |
token to authorize the request. |
| 21 |
""" |
| 22 |
|
| 23 |
openapi_type: str = "apiKey" |
| 24 |
scope = None |
| 25 |
|
| 26 |
def __init__(self, scope: str | list | dict) -> None: |
| 27 |
"""The scope passed can either be: |
| 28 |
|
| 29 |
- a single scope (``str``), |
| 30 |
- a list of scopes, all of which should be granted. |
| 31 |
- a list of scope lists. Your token should match at least all scopes of one of the scope lists. |
| 32 |
- A dictionary, with the request method (e.g. ``GET``) as key, and one |
| 33 |
of the scope values from the previous bullet. The scopes to match are |
| 34 |
then dynamically selected based on the request. |
| 35 |
""" |
| 36 |
super().__init__() |
| 37 |
self.scope = scope |
| 38 |
|
| 39 |
def __call__(self, request: HttpRequest): |
| 40 |
server = get_server() |
| 41 |
orequest = extract_params(request) |
| 42 |
valid, _ = server.verify_request(*orequest, scopes=[]) |
| 43 |
if not valid: |
| 44 |
return None |
| 45 |
access_token = get_validator_context().access_token |
| 46 |
if not is_scope_granted(self.scope, access_token, request.method): |
| 47 |
return None |
| 48 |
if access_token: |
| 49 |
resources = access_token.get_resources() |
| 50 |
if not is_resources_subset( |
| 51 |
[request.build_absolute_uri(request.path)], resources |
| 52 |
): |
| 53 |
raise HttpError(403, "Invalid target resource.") |
| 54 |
if access_token.user: |
| 55 |
request.user = access_token.user |
| 56 |
return access_token |