Debian Codegraph @

docs/examples/token_storage/dynamodb_token_storage.py

raw
1 from __future__ import annotations
2
3 import argparse
4 import time
5 import typing as t
6
7 import boto3
8
9 import globus_sdk
10 from globus_sdk.token_storage import StorageAdapter
11
12 CLIENT_ID = "61338d24-54d5-408f-a10d-66c06b59f6d2"
13 tablename = "example-globus-tokenstorage"
14
15 parser = argparse.ArgumentParser()
16 parser.add_argument(
17 "--create",
18 action="store_true",
19 )
20
21 boto_client = boto3.client("dynamodb")
22 auth_client = globus_sdk.NativeAppAuthClient(CLIENT_ID)
23
24
25 class DynamoDBStorageAdapter(StorageAdapter):
26 def __init__(self, client, tablename: str, namespace: str = "DEFAULT") -> None:
27 """
28 :param client: A boto3 DyanmoDB client to use
29 :param tablename: The name of the dynamodb table to use
30 :param namespace: A namespace for all keys within this storage.
31 Setting up explicit namespacing allows for multiple storage
32 adapters for multiple users or applications to share a table.
33 """
34 self.client = client
35 self.tablename = tablename
36 self.namespace = namespace
37
38 def _compute_key(self, resource_server: str) -> str:
39 """
40 Compute the 'token_data_id' used for storage and retrieval
41 vis-a-vis a specific resource_server/namespace combination.
42
43 This is defined as a simple delimited string which starts with the
44 namespace given.
45
46 Globus keys tokens by the ``resource_server`` string, but also has
47 additional context about which user and application were being
48 used. For the storage adapter, we will need to use namespacing to
49 separate users.
50
51 Consider setting ``namespace`` to a value like a user ID or a
52 combination of user ID and authentication context.
53 """
54 return f"{self.namespace}:{resource_server}"
55
56 def store(self, token_response: globus_sdk.OAuthTokenResponse) -> None:
57 for resource_server, token_data in token_response.by_resource_server.items():
58 key = self._compute_key(resource_server)
59 dynamo_item = {
60 "token_data_id": {"S": key},
61 "resource_server": {"S": resource_server},
62 "access_token": {"S": token_data["access_token"]},
63 "refresh_token": {"S": token_data["refresh_token"]},
64 "expires_at_seconds": {"N": str(token_data["expires_at_seconds"])},
65 "scope": {"S": token_data["scope"]},
66 }
67 # avoid setting `refresh_token` if it is null (meaning the
68 # login flow used access tokens only)
69 if token_data["refresh_token"] is None:
70 del dynamo_item["refresh_token"]
71
72 self.client.put_item(TableName=self.tablename, Item=dynamo_item)
73
74 def get_token_data(self, resource_server: str) -> dict[str, t.Any] | None:
75 key = self._compute_key(resource_server)
76
77 wrapped_item = self.client.get_item(
78 TableName=self.tablename,
79 Key={"token_data_id": {"S": key}},
80 ConsistentRead=True,
81 )
82 if "Item" not in wrapped_item:
83 return None
84
85 dynamo_item = wrapped_item["Item"]
86 return {
87 "resource_server": dynamo_item["resource_server"]["S"],
88 "access_token": dynamo_item["access_token"]["S"],
89 "refresh_token": dynamo_item.get("refresh_token", {"S": None})["S"],
90 "expires_at_seconds": int(dynamo_item["expires_at_seconds"]["N"]),
91 "scope": dynamo_item["scope"]["S"],
92 }
93
94
95 def create_table():
96 # create a table with a key of "token_data_id"
97 # this is a nonspecific string key which we will compute
98 #
99 # the relationship of "token_data_id" to the token will be explained below
100 boto_client.create_table(
101 TableName=tablename,
102 KeySchema=[{"AttributeName": "token_data_id", "KeyType": "HASH"}],
103 AttributeDefinitions=[{"AttributeName": "token_data_id", "AttributeType": "S"}],
104 BillingMode="PROVISIONED",
105 ProvisionedThroughput={"ReadCapacityUnits": 5, "WriteCapacityUnits": 5},
106 )
107 print(f"'{tablename}' create in progress.")
108
109 # poll status until the table is "ACTIVE"
110 print("Waiting for active status (Ctrl+C to cancel)...", end="", flush=True)
111 status = None
112 while status != "ACTIVE":
113 time.sleep(1)
114 try:
115 r = boto_client.describe_table(TableName=tablename)
116 except boto_client.exceptions.ResourceNotFoundException:
117 continue
118 print(".", end="", flush=True)
119 status = r["Table"]["TableStatus"]
120 print("ok")
121
122
123 def do_login_flow(storage: StorageAdapter):
124 auth_client.oauth2_start_flow(
125 requested_scopes=globus_sdk.GroupsClient.scopes.view_my_groups_and_memberships,
126 refresh_tokens=True,
127 )
128 authorize_url = auth_client.oauth2_get_authorize_url()
129 print(f"Please go to this URL and login:\n\n{authorize_url}\n")
130 auth_code = input("Please enter the code here: ").strip()
131 tokens = auth_client.oauth2_exchange_code_for_tokens(auth_code)
132 storage.store(tokens)
133 return tokens.by_resource_server[globus_sdk.GroupsClient.resource_server]
134
135
136 def group_list(storage: StorageAdapter):
137 tokens = storage.get_token_data(globus_sdk.GroupsClient.resource_server)
138 if tokens is None:
139 tokens = do_login_flow(storage)
140
141 authorizer = globus_sdk.RefreshTokenAuthorizer(
142 tokens["refresh_token"],
143 auth_client,
144 access_token=tokens["access_token"],
145 expires_at=tokens["expires_at_seconds"],
146 on_refresh=storage.store,
147 )
148 groups_client = globus_sdk.GroupsClient(authorizer=authorizer)
149 print("ID,Name,Type,Session Enforcement,Roles")
150 for group in groups_client.get_my_groups():
151 # parse the group to get data for output
152 if group.get("enforce_session"):
153 session_enforcement = "strict"
154 else:
155 session_enforcement = "not strict"
156 roles = ",".join({m["role"] for m in group["my_memberships"]})
157
158 print(
159 ",".join(
160 [
161 group["id"],
162 group["name"],
163 group["group_type"],
164 session_enforcement,
165 roles,
166 ]
167 )
168 )
169
170
171 if __name__ == "__main__":
172 args = parser.parse_args()
173 if args.create:
174 create_table()
175 else:
176 storage = DynamoDBStorageAdapter(boto_client, tablename)
177 group_list(storage)