Debian Codegraph @

src/globus_sdk/authorizers/refresh_token.py

raw
1 from __future__ import annotations
2
3 import logging
4 import typing as t
5
6 import globus_sdk
7
8 from .renewing import RenewingAuthorizer
9
10 log = logging.getLogger(__name__)
11
12
13 class RefreshTokenAuthorizer(
14 RenewingAuthorizer["globus_sdk.OAuthRefreshTokenResponse"]
15 ):
16 """
17 Implements Authorization using a Refresh Token to periodically fetch
18 renewed Access Tokens. It may be initialized with an Access Token, or it
19 will fetch one the first time that ``get_authorization_header()`` is
20 called.
21
22 Example usage looks something like this:
23
24 .. code-block:: pycon
25
26 >>> import globus_sdk
27 >>> auth_client = globus_sdk.ConfidentialAppAuthClient(client_id=..., client_secret=...)
28 >>> # do some flow to get a refresh token from auth_client
29 >>> rt_authorizer = globus_sdk.RefreshTokenAuthorizer(refresh_token, auth_client)
30 >>> # create a new client
31 >>> transfer_client = globus_sdk.TransferClient(authorizer=rt_authorizer)
32
33 Anything which inherits from :class:`BaseClient <globus_sdk.BaseClient>`
34 will automatically support usage of the ``RefreshTokenAuthorizer``.
35
36 :param refresh_token: Refresh Token for Globus Auth
37 :param auth_client: ``AuthClient`` capable of using the ``refresh_token``
38 :param access_token: Initial Access Token to use, only used if ``expires_at`` is
39 also set
40 :param expires_at: Expiration time for the starting ``access_token`` expressed as a
41 POSIX timestamp (i.e. seconds since the epoch)
42 :param on_refresh: A callback which is triggered any time this authorizer fetches a
43 new access_token. The ``on_refresh`` callable is invoked on the
44 :class:`globus_sdk.OAuthRefreshTokenResponse` object resulting from the token being
45 refreshed. It should take only one argument, the token response object.
46 This is useful for implementing storage for Access Tokens, as the
47 ``on_refresh`` callback can be used to update the Access Tokens and
48 their expiration times.
49 """ # noqa: E501
50
51 def __init__(
52 self,
53 refresh_token: str,
54 auth_client: globus_sdk.AuthLoginClient,
55 *,
56 access_token: str | None = None,
57 expires_at: int | None = None,
58 on_refresh: (
59 None | t.Callable[[globus_sdk.OAuthRefreshTokenResponse], t.Any]
60 ) = None,
61 ) -> None:
62 log.debug(
63 "Setting up RefreshTokenAuthorizer with auth_client="
64 f"[instance:{id(auth_client)}]"
65 )
66 # per type checkers, this is unreachable... but it is, of course, reachable...
67 # that's... the point
68 if isinstance(auth_client, globus_sdk.AuthClient): # type: ignore[unreachable]
69 raise globus_sdk.GlobusSDKUsageError(
70 "RefreshTokenAuthorizer requires an AuthLoginClient, not an "
71 "AuthClient. In past versions of the SDK, it was possible to "
72 "use an AuthClient if it was correctly authorized, but this is "
73 "no longer allowed. "
74 "Proper usage should typically use a NativeAppAuthClient or "
75 "ConfidentialAppAuthClient."
76 )
77
78 # required for _get_token_data
79 self.refresh_token = refresh_token
80 self.auth_client = auth_client
81
82 super().__init__(access_token, expires_at, on_refresh)
83
84 def _get_token_response(self) -> globus_sdk.OAuthRefreshTokenResponse:
85 """
86 Make a refresh token grant
87 """
88 return self.auth_client.oauth2_refresh_token(self.refresh_token)
89
90 def _extract_token_data(
91 self, res: globus_sdk.OAuthRefreshTokenResponse
92 ) -> dict[str, t.Any]:
93 """
94 Get the tokens .by_resource_server,
95 Ensure that only one token was gotten, and return that token.
96
97 If the token_data includes a "refresh_token" field, update self.refresh_token to
98 that value.
99 """
100 token_data_list = list(res.by_resource_server.values())
101 if len(token_data_list) != 1:
102 raise ValueError(
103 "Attempting refresh for refresh token authorizer "
104 "didn't return exactly one token. Possible service error."
105 )
106
107 token_data = next(iter(token_data_list))
108
109 # handle refresh_token being present
110 # mandated by OAuth2: https://tools.ietf.org/html/rfc6749#section-6
111 if "refresh_token" in token_data:
112 self.refresh_token = token_data["refresh_token"]
113
114 return token_data