Skip to content

Commit ff571ef

Browse files
authored
Merge branch 'main' into feature/stage-out-updates
2 parents 18b5241 + c2f9f1d commit ff571ef

File tree

2 files changed

+61
-37
lines changed

2 files changed

+61
-37
lines changed

libs/unity-py/CHANGELOG.md

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,17 @@ All notable changes to this project will be documented in this file.
55
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
66
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
77

8-
## [0.12.0] - 2025-06-06
8+
## [0.12.0] - 2025-06-10
99

1010
### Added
1111
* Introduce a new class as part of stage-out process: STACCollectionCreator class - Utility for creating STAC Collections from file lists
1212

13+
## [0.11.1] - 2025-06-09
14+
15+
### Added
16+
* Cognito token fetching now appropriately stores and checks token expiration on token use.
17+
18+
1319
## [0.11.0] - 2025-05-19
1420

1521
### Added

libs/unity-py/unity_sds_client/unity_session.py

Lines changed: 54 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
1-
import os
21
import getpass
32
import json
4-
import requests
5-
3+
import os
64
from configparser import ConfigParser
5+
from datetime import datetime, timedelta
6+
7+
import requests
78
from unity_sds_client.unity_environments import UnityEnvironments
89
from unity_sds_client.unity_exception import UnityException
910

1011

11-
1212
class UnitySession(object):
1313
"""
1414
passable session object containing configuration, auth objects, and environment.
@@ -34,8 +34,10 @@ def __init__(self, env: UnityEnvironments, config: ConfigParser):
3434
self._config = config
3535

3636
# set up unity authentication
37-
self._auth = UnityAuth(self._config.get(env, "client_id"), self._config.get(env, "auth_endpoint"))
38-
self._unity_href = self._config.get(env, "unity_href")
37+
self._auth = UnityAuth(
38+
self._config.get(env, "client_id"), self._config.get(env, "auth_endpoint")
39+
)
40+
self._unity_href = self._config.get(env, "unity_href")
3941

4042
self._project = None
4143
self._venue = None
@@ -63,19 +65,18 @@ def get_service_endpoint(self, section, setting):
6365
def get_unity_href(self):
6466
"""convenience method for getting the unity href.
6567
66-
Parameters
67-
----------
68-
none
68+
Parameters
69+
----------
70+
none
6971
70-
Returns
71-
-------
72-
str
73-
the url to the unity top url
72+
Returns
73+
-------
74+
str
75+
the url to the unity top url
7476
75-
"""
77+
"""
7678
return self._unity_href
7779

78-
7980
def get_auth(self):
8081
"""Returns the auth object in use by the session
8182
@@ -99,28 +100,35 @@ def get_config(self):
99100

100101
def get_project(self):
101102
if self._project is None:
102-
raise UnityException("session variables project and venue or venue_id are required to interact with a "
103-
"processing service.")
103+
raise UnityException(
104+
"session variables project and venue or venue_id are required to interact with a "
105+
"processing service."
106+
)
104107
else:
105108
return self._project
106109

107110
def get_venue(self):
108111
if self._venue is None:
109-
raise UnityException("session variables project and venue or venue_id are required to interact with a "
110-
"processing service.")
112+
raise UnityException(
113+
"session variables project and venue or venue_id are required to interact with a "
114+
"processing service."
115+
)
111116
else:
112117
return self._venue
113118

114119
def get_venue_id(self):
115120
if self._venue_id is None:
116121
if self._project is None or self._venue is None:
117-
raise UnityException("session variables project and venue or venue_id are required to interact with a "
118-
"processing service.")
122+
raise UnityException(
123+
"session variables project and venue or venue_id are required to interact with a "
124+
"processing service."
125+
)
119126
else:
120127
return self._project + "/" + self._venue
121128
else:
122129
return self._venue_id
123130

131+
124132
class UnityAuth(object):
125133
"""
126134
Unity Auth object for handling cognito authentication on behalf of all service wrappers.
@@ -132,14 +140,14 @@ class UnityAuth(object):
132140
# The auth_json is template for authorizing with AWS Cognito for a token that can be used for calls to the
133141
# data service. For now this is just an empty data structure. You will be prompted for your username and password
134142
# in a few steps.
135-
auth_json = '''{
143+
auth_json = """{
136144
"AuthParameters" : {
137145
"USERNAME" : "",
138146
"PASSWORD" : ""
139147
},
140148
"AuthFlow" : "USER_PASSWORD_AUTH",
141149
"ClientId" : ""
142-
}'''
150+
}"""
143151

144152
def __init__(self, client_id, auth_endpoint):
145153
"""initialize the Unity Auth class. The initialization looks for username/passwords in the following locations:
@@ -165,11 +173,11 @@ def __init__(self, client_id, auth_endpoint):
165173
# order of operations:
166174
# environment
167175
# netrc? //todo
168-
self._user = os.getenv('UNITY_USER', None)
169-
self._password = os.getenv('UNITY_PASSWORD', None)
176+
self._user = os.getenv("UNITY_USER", None)
177+
self._password = os.getenv("UNITY_PASSWORD", None)
170178

171179
if None in [self._user, self._password]:
172-
username = input('Please enter your Unity username: ')
180+
username = input("Please enter your Unity username: ")
173181
password = getpass.getpass("Please enter your Unity password: ")
174182
self._user = username
175183
self._password = password
@@ -190,6 +198,7 @@ def get_token(self):
190198

191199
return self._token
192200

201+
@staticmethod
193202
def _is_expired(expiration_date):
194203
"""Convenience method for checking if a token is expired. static method
195204
@@ -206,9 +215,9 @@ def _is_expired(expiration_date):
206215
"""
207216
if expiration_date is None:
208217
return True
209-
else:
210-
# TODO
211-
return False
218+
elif expiration_date <= datetime.now():
219+
return True
220+
return False
212221

213222
def _get_unity_token(self):
214223
"""Queries the backing service for a new API Token
@@ -220,14 +229,23 @@ def _get_unity_token(self):
220229
221230
"""
222231
aj = json.loads(self.auth_json)
223-
aj['AuthParameters']['USERNAME'] = self._user
224-
aj['AuthParameters']['PASSWORD'] = self._password
225-
aj['ClientId'] =self._client_id
232+
aj["AuthParameters"]["USERNAME"] = self._user
233+
aj["AuthParameters"]["PASSWORD"] = self._password
234+
aj["ClientId"] = self._client_id
226235
try:
227-
response = requests.post(self._endpoint, headers={"Content-Type":"application/x-amz-json-1.1", "X-Amz-Target":"AWSCognitoIdentityProviderService.InitiateAuth"}, json=aj)
236+
response = requests.post(
237+
self._endpoint,
238+
headers={
239+
"Content-Type": "application/x-amz-json-1.1",
240+
"X-Amz-Target": "AWSCognitoIdentityProviderService.InitiateAuth",
241+
},
242+
json=aj,
243+
)
228244
json_resp = response.json()
229-
self._token = json_resp['AuthenticationResult']['AccessToken']
230-
self._token_expiration = json_resp['AuthenticationResult']['AccessToken']
231-
except:
245+
self._token = json_resp["AuthenticationResult"]["AccessToken"]
246+
self._token_expiration = datetime.now() + timedelta(
247+
seconds=int(json_resp["AuthenticationResult"]["ExpiresIn"])
248+
)
249+
except Exception:
232250
print("Error, check username and password and try again.")
233251
return self._token

0 commit comments

Comments
 (0)