1
- import os
2
1
import getpass
3
2
import json
4
- import requests
5
-
3
+ import os
6
4
from configparser import ConfigParser
5
+ from datetime import datetime , timedelta
6
+
7
+ import requests
7
8
from unity_sds_client .unity_environments import UnityEnvironments
8
9
from unity_sds_client .unity_exception import UnityException
9
10
10
11
11
-
12
12
class UnitySession (object ):
13
13
"""
14
14
passable session object containing configuration, auth objects, and environment.
@@ -34,8 +34,10 @@ def __init__(self, env: UnityEnvironments, config: ConfigParser):
34
34
self ._config = config
35
35
36
36
# 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" )
39
41
40
42
self ._project = None
41
43
self ._venue = None
@@ -63,19 +65,18 @@ def get_service_endpoint(self, section, setting):
63
65
def get_unity_href (self ):
64
66
"""convenience method for getting the unity href.
65
67
66
- Parameters
67
- ----------
68
- none
68
+ Parameters
69
+ ----------
70
+ none
69
71
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
74
76
75
- """
77
+ """
76
78
return self ._unity_href
77
79
78
-
79
80
def get_auth (self ):
80
81
"""Returns the auth object in use by the session
81
82
@@ -99,28 +100,35 @@ def get_config(self):
99
100
100
101
def get_project (self ):
101
102
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
+ )
104
107
else :
105
108
return self ._project
106
109
107
110
def get_venue (self ):
108
111
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
+ )
111
116
else :
112
117
return self ._venue
113
118
114
119
def get_venue_id (self ):
115
120
if self ._venue_id is None :
116
121
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
+ )
119
126
else :
120
127
return self ._project + "/" + self ._venue
121
128
else :
122
129
return self ._venue_id
123
130
131
+
124
132
class UnityAuth (object ):
125
133
"""
126
134
Unity Auth object for handling cognito authentication on behalf of all service wrappers.
@@ -132,14 +140,14 @@ class UnityAuth(object):
132
140
# The auth_json is template for authorizing with AWS Cognito for a token that can be used for calls to the
133
141
# data service. For now this is just an empty data structure. You will be prompted for your username and password
134
142
# in a few steps.
135
- auth_json = ''' {
143
+ auth_json = """ {
136
144
"AuthParameters" : {
137
145
"USERNAME" : "",
138
146
"PASSWORD" : ""
139
147
},
140
148
"AuthFlow" : "USER_PASSWORD_AUTH",
141
149
"ClientId" : ""
142
- }'''
150
+ }"""
143
151
144
152
def __init__ (self , client_id , auth_endpoint ):
145
153
"""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):
165
173
# order of operations:
166
174
# environment
167
175
# 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 )
170
178
171
179
if None in [self ._user , self ._password ]:
172
- username = input (' Please enter your Unity username: ' )
180
+ username = input (" Please enter your Unity username: " )
173
181
password = getpass .getpass ("Please enter your Unity password: " )
174
182
self ._user = username
175
183
self ._password = password
@@ -190,6 +198,7 @@ def get_token(self):
190
198
191
199
return self ._token
192
200
201
+ @staticmethod
193
202
def _is_expired (expiration_date ):
194
203
"""Convenience method for checking if a token is expired. static method
195
204
@@ -206,9 +215,9 @@ def _is_expired(expiration_date):
206
215
"""
207
216
if expiration_date is None :
208
217
return True
209
- else :
210
- # TODO
211
- return False
218
+ elif expiration_date <= datetime . now () :
219
+ return True
220
+ return False
212
221
213
222
def _get_unity_token (self ):
214
223
"""Queries the backing service for a new API Token
@@ -220,14 +229,23 @@ def _get_unity_token(self):
220
229
221
230
"""
222
231
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
226
235
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
+ )
228
244
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 :
232
250
print ("Error, check username and password and try again." )
233
251
return self ._token
0 commit comments