Debian Codegraph @

src/globus_sdk/token_storage/legacy/base.py

raw
1 from __future__ import annotations
2
3 import abc
4 import contextlib
5 import os
6 import typing as t
7
8 import globus_sdk
9
10
11 class StorageAdapter(metaclass=abc.ABCMeta):
12 @abc.abstractmethod
13 def store(self, token_response: globus_sdk.OAuthTokenResponse) -> None:
14 """
15 Store an `OAuthTokenResponse` in the underlying storage for this adapter.
16
17 :param token_response: The token response to store
18 """
19
20 @abc.abstractmethod
21 def get_token_data(self, resource_server: str) -> dict[str, t.Any] | None:
22 """
23 Lookup token data for a resource server
24
25 Either returns a dict with the access token, refresh token (optional), and
26 expiration time, or returns ``None``, indicating that there was no data for that
27 resource server.
28
29 :param resource_server: The resource_server string which uniquely identifies the
30 token data to retriever from storage
31 """
32
33 def on_refresh(self, token_response: globus_sdk.OAuthTokenResponse) -> None:
34 """
35 By default, the on_refresh handler for a token storage adapter simply
36 stores the token response.
37
38 :param token_response: The token response received from the refresh
39 """
40 self.store(token_response)
41
42
43 class FileAdapter(StorageAdapter, metaclass=abc.ABCMeta):
44 """
45 File adapters are for single-user cases, where we can assume that there's a
46 simple file-per-user and users are only ever attempting to read their own
47 files.
48 """
49
50 filename: str
51
52 def file_exists(self) -> bool:
53 """
54 Check if the file used by this file storage adapter exists.
55 """
56 return os.path.exists(self.filename)
57
58 @contextlib.contextmanager
59 def user_only_umask(self) -> t.Iterator[None]:
60 """
61 A context manager to deny rwx to Group and World, x to User
62
63 This does not create a file, but ensures that if a file is created while in the
64 context manager, its permissions will be correct on unix systems.
65
66 .. note::
67
68 On Windows, this has no effect. To control the permissions on files used for
69 token storage, use ``%LOCALAPPDATA%`` or ``%APPDATA%``.
70 These directories should only be accessible to the current user.
71 """
72 old_umask = os.umask(0o177)
73 try:
74 yield
75 finally:
76 os.umask(old_umask)