14
14
TOKENS = {}
15
15
16
16
17
+ class ConfigurationError (Exception ):
18
+ def __init__ (self , msg ):
19
+ self .msg = msg
20
+
21
+ def __str__ (self ):
22
+ return 'Configuration error: {}' .format (self .msg )
23
+
24
+
25
+ class InvalidCredentialsError (Exception ):
26
+ def __init__ (self , msg ):
27
+ self .msg = msg
28
+
29
+ def __str__ (self ):
30
+ return 'Invalid OAuth credentials: {}' .format (self .msg )
31
+
32
+
17
33
def init_fixed_tokens_from_env ():
18
34
env_val = os .environ .get ('OAUTH2_ACCESS_TOKENS' , '' )
19
35
for part in filter (None , env_val .split (',' )):
@@ -36,27 +52,47 @@ def start():
36
52
pass
37
53
38
54
55
+ def read_credentials (path ):
56
+ user_path = os .path .join (path , 'user.json' )
57
+ try :
58
+ with open (user_path ) as fd :
59
+ user_data = json .load (fd )
60
+ except Exception as e :
61
+ raise InvalidCredentialsError ('Failed to read {}: {}' .format (user_path , e ))
62
+
63
+ client_path = os .path .join (path , 'client.json' )
64
+ try :
65
+ with open (client_path ) as fd :
66
+ client_data = json .load (fd )
67
+ except Exception as e :
68
+ raise InvalidCredentialsError ('Failed to read {}: {}' .format (client_path , e ))
69
+
70
+ return user_data , client_data
71
+
72
+
39
73
def refresh (token_name ):
40
74
logger .info ('Refreshing access token "%s"..' , token_name )
41
75
token = TOKENS [token_name ]
42
76
path = CONFIG ['dir' ]
43
77
url = CONFIG ['url' ]
44
78
45
79
if not url :
46
- raise Exception ('Missing OAuth access token URL. ' +
47
- 'Either set OAUTH_ACCESS_TOKEN_URL or use tokens.configure(url=..).' )
48
-
49
- with open (os .path .join (path , 'user.json' )) as fd :
50
- user_data = json .load (fd )
51
- with open (os .path .join (path , 'client.json' )) as fd :
52
- client_data = json .load (fd )
53
- body = {'grant_type' : 'password' ,
54
- 'username' : user_data .get ('application_username' ),
55
- 'password' : user_data .get ('application_password' ),
56
- 'scope' : ' ' .join (token ['scopes' ])}
57
-
58
- r = requests .post (url , data = body ,
59
- auth = (client_data .get ('client_id' ), client_data .get ('client_secret' )))
80
+ raise ConfigurationError ('Missing OAuth access token URL. ' +
81
+ 'Either set OAUTH_ACCESS_TOKEN_URL or use tokens.configure(url=..).' )
82
+
83
+ user_data , client_data = read_credentials (path )
84
+
85
+ try :
86
+ body = {'grant_type' : 'password' ,
87
+ 'username' : user_data ['application_username' ],
88
+ 'password' : user_data ['application_password' ],
89
+ 'scope' : ' ' .join (token ['scopes' ])}
90
+
91
+ auth = (client_data ['client_id' ], client_data ['client_secret' ])
92
+ except KeyError as e :
93
+ raise InvalidCredentialsError ('Missing key: {}' .format (e ))
94
+
95
+ r = requests .post (url , data = body , auth = auth )
60
96
r .raise_for_status ()
61
97
data = r .json ()
62
98
token ['data' ] = data
0 commit comments