Skip to content

Commit 7ae7588

Browse files
Tox fixes
1 parent 20630be commit 7ae7588

File tree

5 files changed

+64
-96
lines changed

5 files changed

+64
-96
lines changed

SoftLayer/API.py

Lines changed: 17 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -6,19 +6,20 @@
66
:license: MIT, see LICENSE for more details.
77
"""
88
# pylint: disable=invalid-name
9+
import time
10+
import warnings
11+
912
import json
1013
import logging
1114
import requests
12-
import warnings
13-
import time
15+
1416

1517
from SoftLayer import auth as slauth
1618
from SoftLayer import config
1719
from SoftLayer import consts
1820
from SoftLayer import exceptions
1921
from SoftLayer import transports
2022

21-
from pprint import pprint as pp
2223
LOGGER = logging.getLogger(__name__)
2324
API_PUBLIC_ENDPOINT = consts.API_PUBLIC_ENDPOINT
2425
API_PRIVATE_ENDPOINT = consts.API_PRIVATE_ENDPOINT
@@ -188,7 +189,7 @@ def __init__(self, auth=None, transport=None, config_file=None):
188189
verify=self.settings['softlayer'].getboolean('verify'),
189190
)
190191

191-
self.transport = transport
192+
self.transport = transport
192193

193194
def authenticate_with_password(self, username, password,
194195
security_question_id=None,
@@ -357,15 +358,15 @@ def __repr__(self):
357358
def __len__(self):
358359
return 0
359360

361+
360362
class IAMClient(BaseClient):
361363
"""IBM ID Client for using IAM authentication
362364
363365
:param auth: auth driver that looks like SoftLayer.auth.AuthenticationBase
364366
:param transport: An object that's callable with this signature: transport(SoftLayer.transports.Request)
365367
"""
366368

367-
368-
def authenticate_with_password(self, username, password):
369+
def authenticate_with_password(self, username, password, security_question_id=None, security_question_answer=None):
369370
"""Performs IBM IAM Username/Password Authentication
370371
371372
:param string username: your IBMid username
@@ -394,14 +395,14 @@ def authenticate_with_password(self, username, password):
394395
auth=requests.auth.HTTPBasicAuth('bx', 'bx')
395396
)
396397
if response.status_code != 200:
397-
LOGGER.error("Unable to login: {}".format(response.text))
398+
LOGGER.error("Unable to login: %s", response.text)
398399

399400
response.raise_for_status()
400401

401402
tokens = json.loads(response.text)
402403
self.settings['softlayer']['access_token'] = tokens['access_token']
403404
self.settings['softlayer']['refresh_token'] = tokens['refresh_token']
404-
405+
405406
config.write_config(self.settings, self.config_file)
406407
self.auth = slauth.BearerAuthentication('', tokens['access_token'], tokens['refresh_token'])
407408

@@ -434,7 +435,7 @@ def authenticate_with_passcode(self, passcode):
434435
auth=requests.auth.HTTPBasicAuth('bx', 'bx')
435436
)
436437
if response.status_code != 200:
437-
LOGGER.error("Unable to login: {}".format(response.text))
438+
LOGGER.error("Unable to login: %s", response.text)
438439

439440
response.raise_for_status()
440441

@@ -443,7 +444,7 @@ def authenticate_with_passcode(self, passcode):
443444
self.settings['softlayer']['refresh_token'] = tokens['refresh_token']
444445
a_expire = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(tokens['expiration']))
445446
r_expire = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(tokens['refresh_token_expiration']))
446-
LOGGER.warning("Tokens retrieved, expires at {}, Refresh expires at {}".format(a_expire, r_expire))
447+
LOGGER.warning("Tokens retrieved, expires at %s, Refresh expires at %s", a_expire, r_expire)
447448
config.write_config(self.settings, self.config_file)
448449
self.auth = slauth.BearerAuthentication('', tokens['access_token'], tokens['refresh_token'])
449450

@@ -489,16 +490,16 @@ def refresh_iam_token(self, r_token, account_id=None, ims_account=None):
489490
headers=headers,
490491
auth=requests.auth.HTTPBasicAuth('bx', 'bx')
491492
)
492-
493+
493494
if response.status_code != 200:
494-
LOGGER.warning("Unable to refresh IAM Token. {}".format(response.text))
495-
495+
LOGGER.warning("Unable to refresh IAM Token. %s", response.text)
496+
496497
response.raise_for_status()
497-
498+
498499
tokens = json.loads(response.text)
499500
a_expire = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(tokens['expiration']))
500501
r_expire = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(tokens['refresh_token_expiration']))
501-
LOGGER.warning("Successfully refreshed Tokens. Expires at {}, Refresh expires at {}".format(a_expire, r_expire))
502+
LOGGER.warning("Tokens retrieved, expires at %s, Refresh expires at %s", a_expire, r_expire)
502503

503504
self.settings['softlayer']['access_token'] = tokens['access_token']
504505
self.settings['softlayer']['refresh_token'] = tokens['refresh_token']
@@ -513,9 +514,7 @@ def call(self, service, method, *args, **kwargs):
513514
except exceptions.SoftLayerAPIError as ex:
514515

515516
if ex.faultCode == 401:
516-
LOGGER.warning("Token has expired, trying to refresh. {}".format(ex.faultString))
517-
# self.refresh_iam_token(r_token)
518-
# return super().call(service, method, *args, **kwargs)
517+
LOGGER.warning("Token has expired, trying to refresh. %s", ex.faultString)
519518
return ex
520519
else:
521520
raise ex

SoftLayer/CLI/config/setup.py

Lines changed: 16 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,11 @@
11
"""Setup CLI configuration."""
22
# :license: MIT, see LICENSE for more details.
3+
import webbrowser
4+
35
import configparser
46
import json
5-
import requests
67
import os.path
7-
import webbrowser
8+
import requests
89

910
import click
1011

@@ -13,11 +14,9 @@
1314
from SoftLayer.CLI import environment
1415
from SoftLayer.CLI import exceptions
1516
from SoftLayer.CLI import formatting
16-
from SoftLayer import config as base_config
1717
from SoftLayer.consts import USER_AGENT
1818
from SoftLayer import utils
1919

20-
from pprint import pprint as pp
2120

2221
def get_api_key(client, username, secret): # pylint: disable=inconsistent-return-statements
2322
"""Attempts API-Key and password auth to get an API key.
@@ -66,31 +65,26 @@ def cli(env, auth):
6665
"""
6766
username = None
6867
api_key = None
69-
68+
7069
timeout = 0
7170
defaults = config.get_settings_from_client(env.client)
72-
endpoint_url = defaults.get('endpoint_url', 'public')
73-
# endpoint_url = get_endpoint_url(env, defaults.get('endpoint_url', 'public'))
71+
endpoint_url = get_endpoint_url(env, defaults.get('endpoint_url', 'public'))
7472
# Get ths username and API key
7573
if auth == 'ibmid':
76-
print("Logging in with IBMid")
7774
username, api_key = ibmid_login(env)
78-
75+
7976
elif auth == 'cloud_key':
8077
username = 'apikey'
81-
secret = env.input('Classic Infrastructue API Key', default=defaults['api_key'])
78+
secret = env.getpass('Classic Infrastructue API Key', default=defaults['api_key'])
8279
new_client = SoftLayer.Client(username=username, api_key=secret, endpoint_url=endpoint_url, timeout=timeout)
8380
api_key = get_api_key(new_client, username, secret)
8481

85-
elif auth =='sso':
86-
print("Using SSO for login")
82+
elif auth == 'sso':
8783
username, api_key = sso_login(env)
88-
else:
89-
print("Using a Classic Infrastructure API key")
9084

85+
else:
9186
username = env.input('Classic Infrastructue Username', default=defaults['username'])
92-
secret = env.input('Classic Infrastructue API Key', default=defaults['api_key'])
93-
87+
secret = env.getpass('Classic Infrastructue API Key', default=defaults['api_key'])
9488
new_client = SoftLayer.Client(username=username, api_key=secret, endpoint_url=endpoint_url, timeout=timeout)
9589
api_key = get_api_key(new_client, username, secret)
9690

@@ -148,32 +142,26 @@ def get_endpoint_url(env, endpoint='public'):
148142
endpoint_url = env.input('Endpoint URL', default=endpoint)
149143
else:
150144
endpoint_url = endpoint_type
151-
152-
153145
return endpoint_url
154146

147+
155148
def ibmid_login(env):
156149
"""Uses an IBMid and Password to get an access token, and that access token to get an API key"""
157150
email = env.input("Email").strip()
158151
password = env.getpass("Password").strip()
159152

160-
account_id = ''
161-
ims_id = ''
162-
sl_config = base_config.get_config(env.config_file)
163-
# tokens = {'access_token': sl_config['softlayer']['access_token'], 'refresh_token': sl_config['softlayer']['refresh_token']}
164153
client = SoftLayer.API.IAMClient(config_file=env.config_file)
165-
154+
166155
# STEP 1: Get the base IAM Token with a username/password
167156
tokens = client.authenticate_with_password(email, password)
168157

169158
# STEP 2: Figure out which account we want to use
170159
account = get_accounts(env, tokens['access_token'])
171-
160+
172161
# STEP 3: Refresh Token, using a specific account this time.
173162
tokens = client.refresh_iam_token(tokens['refresh_token'], account['account_id'], account['ims_id'])
174163

175164
# STEP 4: Get or create the Classic Infrastructure API key
176-
# client.authenticate_with_iam_token(tokens['access_token'])
177165
user = client.call('SoftLayer_Account', 'getCurrentUser', mask="mask[id,username,apiAuthenticationKeys]")
178166

179167
if len(user.get('apiAuthenticationKeys', [])) == 0:
@@ -220,12 +208,11 @@ def get_accounts(env, a_token):
220208
ims_id = "Unlinked"
221209
env.fout("{}: {} ({})".format(counter, utils.lookup(selected, 'entity', 'name'), ims_id))
222210
counter = counter + 1
223-
ims_id = None # Reset ims_id to avoid any mix-match or something.
211+
ims_id = None # Reset ims_id to avoid any mix-match or something.
224212
choice = click.prompt('Enter a number', type=int)
225213
# Test to make sure choice is not out of bounds...
226214
selected = accounts['resources'][choice - 1]
227215

228-
229216
account_id = utils.lookup(selected, 'metadata', 'guid')
230217
links = utils.lookup(selected, 'metadata', 'linked_accounts') or []
231218
for link in links:
@@ -256,11 +243,9 @@ def get_sso_url():
256243
data = json.loads(response.text)
257244
return data.get('passcode_endpoint')
258245

246+
259247
def sso_login(env):
260248
"""Uses a SSO token to get a SL apikey"""
261-
account_id = ''
262-
ims_id = ''
263-
264249
passcode_url = get_sso_url()
265250
env.fout("Get a one-time code from {} to proceed.".format(passcode_url))
266251
open_browser = env.input("Open the URL in the default browser? [Y/n]", default='Y')
@@ -287,4 +272,4 @@ def sso_login(env):
287272
api_key = client.call('User_Customer', 'addApiAuthenticationKey', id=user['id'])
288273
else:
289274
api_key = user['apiAuthenticationKeys'][0]['authenticationKey']
290-
return user.get('username'), api_key
275+
return user.get('username'), api_key

SoftLayer/auth.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,6 @@
77
"""
88
# pylint: disable=no-self-use
99

10-
from SoftLayer import config
11-
1210
__all__ = [
1311
'BasicAuthentication',
1412
'TokenAuthentication',
@@ -112,6 +110,7 @@ def get_request(self, request):
112110
def __repr__(self):
113111
return "BasicHTTPAuthentication(username=%r)" % self.username
114112

113+
115114
class BearerAuthentication(AuthenticationBase):
116115
"""Bearer Token authentication class.
117116
@@ -121,7 +120,7 @@ class BearerAuthentication(AuthenticationBase):
121120

122121
def __init__(self, username, token, r_token=None):
123122
"""For using IBM IAM authentication
124-
123+
125124
:param username str: Not really needed, will be set to their current username though for logging
126125
:param token str: the IAM Token
127126
:param r_token str: The refresh Token, optional
@@ -137,4 +136,4 @@ def get_request(self, request):
137136
return request
138137

139138
def __repr__(self):
140-
return "BearerAuthentication(username={}, token={})".format(self.username, self.api_key)
139+
return "BearerAuthentication(username={}, token={})".format(self.username, self.api_key)

SoftLayer/config.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212

1313
LOGGER = logging.getLogger(__name__)
1414

15+
1516
def get_client_settings_args(**kwargs):
1617
"""Retrieve client settings from user-supplied arguments.
1718
@@ -96,16 +97,18 @@ def get_client_settings(**kwargs):
9697

9798

9899
def get_config(config_file=None):
100+
"""Returns a parsed config object"""
99101
if config_file is None:
100102
config_file = '~/.softlayer'
101103
config = configparser.ConfigParser()
102104
config.read(os.path.expanduser(config_file))
103105
return config
104106

107+
105108
def write_config(configuration, config_file=None):
109+
"""Writes a configuration to config_file"""
106110
if config_file is None:
107111
config_file = '~/.softlayer'
108112
config_file = os.path.expanduser(config_file)
109-
LOGGER.warning("Updating config file {} with new access tokens".format(config_file))
110113
with open(config_file, 'w') as file:
111-
configuration.write(file)
114+
configuration.write(file)

0 commit comments

Comments
 (0)