Skip to content

Пользовательский провайдер аутентификации

Вы можете реализовать собственный поставщик аутентификации, унаследовав его от класса ниже и реализовав необходимые методы.

Bases: ABC

Basic class for all Auth providers.

Constructor is called by FastAPI, and can use Dependency injection mechanism. See :obj:~setup for more details.

Source code in syncmaster/server/providers/auth/base_provider.py
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
class AuthProvider(ABC):
    """Basic class for all Auth providers.

    Constructor is called by FastAPI, and can use Dependency injection mechanism.
    See :obj:`~setup` for more details.
    """

    @classmethod
    @abstractmethod
    def setup(cls, app: FastAPI) -> FastAPI:
        """
        This method is called by :obj:`syncmaster.server.application_factory`.

        Here you should add dependency overrides for auth provider,
        and return new ``app`` object.

        Examples
        --------

        .. code-block::

            from fastapi import FastAPI
            from my_awesome_auth_provider.settings import MyAwesomeAuthProviderSettings
            from syncmaster.server.dependencies import Stub

            class MyAwesomeAuthProvider(AuthProvider):
                def setup(app):
                    app.dependency_overrides[AuthProvider] = MyAwesomeAuthProvider

                    # `settings_object_factory` returns MyAwesomeAuthProviderSettings object
                    app.dependency_overrides[MyAwesomeAuthProviderSettings] = settings_object_factory
                    return app

                def __init__(
                    self,
                    settings: Annotated[MyAwesomeAuthProviderSettings, Depends(Stub(MyAwesomeAuthProviderSettings))],
                ):
                    # settings object is set automatically by FastAPI's dependency_overrides
                    self.settings = settings
        """
        ...

    @abstractmethod
    async def get_current_user(self, access_token: str | None, request: Request) -> User:
        """
        This method should return currently logged in user.

        Parameters
        ----------
        access_token : str
            JWT token got from ``Authorization: Bearer <token>`` header.

        Returns
        -------
        :obj:`syncmaster.server.db.models.User`
            Current user object
        """
        ...

    @abstractmethod
    async def get_token_password_grant(  # noqa: PLR0913
        self,
        grant_type: str | None = None,
        login: str | None = None,
        password: str | None = None,
        scopes: list[str] | None = None,
        client_id: str | None = None,
        client_secret: str | None = None,
    ) -> dict[str, Any]:
        """
        This method should perform authentication and return JWT token.

        Parameters
        ----------
        See:
          * https://auth0.com/docs/get-started/authentication-and-authorization-flow/call-your-api-using-resource-owner-password-flow
          * https://connect2id.com/products/server/docs/api/token

        Returns
        -------
        Dict:
            .. code-block:: python

                {
                    "access_token": "some.jwt.token",
                    "token_type": "bearer",
                    "expires_in": 3600,
                }
        """
        ...

    @abstractmethod
    async def get_token_authorization_code_grant(
        self,
        code: str,
        scopes: list[str] | None = None,
        client_id: str | None = None,
        client_secret: str | None = None,
    ) -> dict[str, Any]:
        """
        Obtain a token using the Authorization Code grant.
        """

    @abstractmethod
    async def logout(self, user: User, refresh_token: str | None) -> None:
        """
        Logout user
        """

get_current_user(access_token, request) abstractmethod async

This method should return currently logged in user.

Parameters

access_token : str JWT token got from Authorization: Bearer <token> header.

Returns

:obj:syncmaster.server.db.models.User Current user object

Source code in syncmaster/server/providers/auth/base_provider.py
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
@abstractmethod
async def get_current_user(self, access_token: str | None, request: Request) -> User:
    """
    This method should return currently logged in user.

    Parameters
    ----------
    access_token : str
        JWT token got from ``Authorization: Bearer <token>`` header.

    Returns
    -------
    :obj:`syncmaster.server.db.models.User`
        Current user object
    """
    ...

get_token_authorization_code_grant(code, scopes=None, client_id=None, client_secret=None) abstractmethod async

Obtain a token using the Authorization Code grant.

Source code in syncmaster/server/providers/auth/base_provider.py
103
104
105
106
107
108
109
110
111
112
113
@abstractmethod
async def get_token_authorization_code_grant(
    self,
    code: str,
    scopes: list[str] | None = None,
    client_id: str | None = None,
    client_secret: str | None = None,
) -> dict[str, Any]:
    """
    Obtain a token using the Authorization Code grant.
    """

get_token_password_grant(grant_type=None, login=None, password=None, scopes=None, client_id=None, client_secret=None) abstractmethod async

This method should perform authentication and return JWT token.

Parameters

See: * https://auth0.com/docs/get-started/authentication-and-authorization-flow/call-your-api-using-resource-owner-password-flow * https://connect2id.com/products/server/docs/api/token

Returns

Dict: .. code-block:: python

    {
        "access_token": "some.jwt.token",
        "token_type": "bearer",
        "expires_in": 3600,
    }
Source code in syncmaster/server/providers/auth/base_provider.py
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
@abstractmethod
async def get_token_password_grant(  # noqa: PLR0913
    self,
    grant_type: str | None = None,
    login: str | None = None,
    password: str | None = None,
    scopes: list[str] | None = None,
    client_id: str | None = None,
    client_secret: str | None = None,
) -> dict[str, Any]:
    """
    This method should perform authentication and return JWT token.

    Parameters
    ----------
    See:
      * https://auth0.com/docs/get-started/authentication-and-authorization-flow/call-your-api-using-resource-owner-password-flow
      * https://connect2id.com/products/server/docs/api/token

    Returns
    -------
    Dict:
        .. code-block:: python

            {
                "access_token": "some.jwt.token",
                "token_type": "bearer",
                "expires_in": 3600,
            }
    """
    ...

logout(user, refresh_token) abstractmethod async

Logout user

Source code in syncmaster/server/providers/auth/base_provider.py
115
116
117
118
119
@abstractmethod
async def logout(self, user: User, refresh_token: str | None) -> None:
    """
    Logout user
    """

setup(app) abstractmethod classmethod

This method is called by :obj:syncmaster.server.application_factory.

Here you should add dependency overrides for auth provider, and return new app object.

Examples

.. code-block::

from fastapi import FastAPI
from my_awesome_auth_provider.settings import MyAwesomeAuthProviderSettings
from syncmaster.server.dependencies import Stub

class MyAwesomeAuthProvider(AuthProvider):
    def setup(app):
        app.dependency_overrides[AuthProvider] = MyAwesomeAuthProvider

        # `settings_object_factory` returns MyAwesomeAuthProviderSettings object
        app.dependency_overrides[MyAwesomeAuthProviderSettings] = settings_object_factory
        return app

    def __init__(
        self,
        settings: Annotated[MyAwesomeAuthProviderSettings, Depends(Stub(MyAwesomeAuthProviderSettings))],
    ):
        # settings object is set automatically by FastAPI's dependency_overrides
        self.settings = settings
Source code in syncmaster/server/providers/auth/base_provider.py
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
@classmethod
@abstractmethod
def setup(cls, app: FastAPI) -> FastAPI:
    """
    This method is called by :obj:`syncmaster.server.application_factory`.

    Here you should add dependency overrides for auth provider,
    and return new ``app`` object.

    Examples
    --------

    .. code-block::

        from fastapi import FastAPI
        from my_awesome_auth_provider.settings import MyAwesomeAuthProviderSettings
        from syncmaster.server.dependencies import Stub

        class MyAwesomeAuthProvider(AuthProvider):
            def setup(app):
                app.dependency_overrides[AuthProvider] = MyAwesomeAuthProvider

                # `settings_object_factory` returns MyAwesomeAuthProviderSettings object
                app.dependency_overrides[MyAwesomeAuthProviderSettings] = settings_object_factory
                return app

            def __init__(
                self,
                settings: Annotated[MyAwesomeAuthProviderSettings, Depends(Stub(MyAwesomeAuthProviderSettings))],
            ):
                # settings object is set automatically by FastAPI's dependency_overrides
                self.settings = settings
    """
    ...