| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
from django.http import HttpRequest |
| 4 |
|
| 5 |
from rest_framework.permissions import BasePermission |
| 6 |
|
| 7 |
from allauth.idp.oidc.internal.scope import is_scope_granted |
| 8 |
from allauth.idp.oidc.models import Token |
| 9 |
|
| 10 |
|
| 11 |
class TokenPermission(BasePermission): |
| 12 |
scope = None |
| 13 |
|
| 14 |
def has_permission(self, request: HttpRequest, view) -> bool: |
| 15 |
access_token = request.auth # type:ignore[attr-defined] |
| 16 |
if ( |
| 17 |
not isinstance(access_token, Token) |
| 18 |
or access_token.type != Token.Type.ACCESS_TOKEN |
| 19 |
): |
| 20 |
return False |
| 21 |
return is_scope_granted(self.scope, access_token, request.method) |
| 22 |
|
| 23 |
@classmethod |
| 24 |
def has_scope(cls, scope: str | list | dict): |
| 25 |
""" |
| 26 |
Constructs and returns specific permission **class** (not instance) |
| 27 |
that checks that the request is authenticated by means of a token (see: |
| 28 |
``TokenAuthentication``), and, that this token has the specified |
| 29 |
``scope`` granted. |
| 30 |
|
| 31 |
The scope passed can either be: |
| 32 |
|
| 33 |
- a single scope (``str``), |
| 34 |
- a list of scopes, all of which should be granted. |
| 35 |
- a list of scope lists. Your token should match at least all scopes of one of the scope lists. |
| 36 |
- A dictionary, with the request method (e.g. ``GET``) as key, and one |
| 37 |
of the scope values from the previous bullet. The scopes to match are |
| 38 |
then dynamically selected based on the request. |
| 39 |
|
| 40 |
""" |
| 41 |
|
| 42 |
class TokenHasScopePermission(cls): # type:ignore[misc,valid-type] |
| 43 |
def __init__(self, *args, **kwargs) -> None: |
| 44 |
super().__init__(*args, **kwargs) |
| 45 |
self.scope = scope |
| 46 |
|
| 47 |
return TokenHasScopePermission |