def get_api_key(username, secret, endpoint_url=None): # Try to use a client with username/api key try: client = Client( username=username, api_key=secret, endpoint_url=endpoint_url, timeout=5) client['Account'].getCurrentUser() return secret except SoftLayerAPIError as e: if 'invalid api token' not in e.faultString.lower(): raise # Try to use a client with username/password client = Client(endpoint_url=endpoint_url, timeout=5) client.authenticate_with_password(username, secret) user_record = client['Account'].getCurrentUser( mask='id, apiAuthenticationKeys') api_keys = user_record['apiAuthenticationKeys'] if len(api_keys) == 0: return client['User_Customer'].addApiAuthenticationKey( id=user_record['id']) return api_keys[0]['authenticationKey']
def get_new_token(credentials): username = lookup(credentials, 'auth', 'passwordCredentials', 'username') credential = lookup(credentials, 'auth', 'passwordCredentials', 'password') # If the 'password' is the right length, treat it as an API api_key if len(credential) == 64: client = Client(username=username, api_key=credential) user = client['Account'].getCurrentUser(mask=USER_MASK) return {'username': username, 'api_key': credential, 'auth_type': 'api_key', 'tenant_id': str(user['accountId']), 'expires': time.time() + (60 * 60 * 24)}, user else: client = Client() client.auth = None try: userId, tokenHash = client.authenticate_with_password(username, credential) user = client['Account'].getCurrentUser(mask=USER_MASK) return {'userId': userId, 'tokenHash': tokenHash, 'auth_type': 'token', 'tenant_id': str(user['accountId']), 'expires': time.time() + (60 * 60 * 24)}, user except SoftLayerAPIError as e: if e.faultCode == 'SoftLayer_Exception_User_Customer_LoginFailed': raise Unauthorized(e.faultString) raise
def authenticate(self, creds): username = lookup(creds, 'auth', 'passwordCredentials', 'username') credential = lookup(creds, 'auth', 'passwordCredentials', 'password') token_id = lookup(creds, 'auth', 'token', 'id') token_auth = None if token_id: token = identity.token_id_driver().token_from_id(token_id) token_driver = identity.token_driver() token_driver.validate_token(token) username = token_driver.username(token) credential = token_driver.credential(token) token_auth = token['auth_type'] == 'token' def assert_tenant(user): tenant = lookup(creds, 'auth', 'tenantId') or lookup(creds, 'auth', 'tenantName') if tenant and str(user['accountId']) != tenant: raise Unauthorized('Invalid username, password or tenant id') # If the 'password' is the right length, treat it as an API api_key if len(credential) == 64: client = Client(username=username, api_key=credential, endpoint_url=cfg.CONF['softlayer']['endpoint'], proxy=cfg.CONF['softlayer']['proxy']) user = client['Account'].getCurrentUser(mask=USER_MASK) assert_tenant(user) return {'user': user, 'credential': credential, 'auth_type': 'api_key'} else: client = Client(endpoint_url=cfg.CONF['softlayer']['endpoint'], proxy=cfg.CONF['softlayer']['proxy']) client.auth = None try: if token_auth: client.auth = TokenAuthentication(token['user_id'], credential) else: userId, tokenHash = client.\ authenticate_with_password(username, credential) user = client['Account'].getCurrentUser(mask=USER_MASK) assert_tenant(user) if token_auth: tokenHash = credential return {'user': user, 'credential': tokenHash, 'auth_type': 'token'} except SoftLayerAPIError as e: if (e.faultCode == "SoftLayer_Exception_User_Customer" "_LoginFailed"): raise Unauthorized(e.faultString) raise
def bind_client(req, resp, kwargs): client = Client(endpoint_url=cfg.CONF['softlayer']['endpoint']) client.auth = None req.env['sl_client'] = client auth_token = req.env.get('auth', None) if auth_token is not None: client.auth = get_auth(auth_token)
def bind_client(req, resp, kwargs): client = Client(endpoint_url=cfg.CONF['softlayer']['endpoint'], proxy=cfg.CONF['softlayer']['proxy']) client.auth = None req.env['sl_client'] = client auth_token = req.env.get('auth', None) if auth_token is not None: client.auth = get_auth(auth_token)
def on_get(self, req, resp, token_id): token_details = get_token_details(token_id, tenant_id=req.get_param('belongsTo')) client = Client(endpoint_url=cfg.CONF['softlayer']['endpoint']) client.auth = get_auth(token_details) user = client['Account'].getCurrentUser(mask='id, username') access = get_access(token_id, token_details, user) resp.status = 200 resp.body = {'access': access}
def authenticate(self, creds): username = lookup(creds, 'auth', 'passwordCredentials', 'username') credential = lookup(creds, 'auth', 'passwordCredentials', 'password') token_id = lookup(creds, 'auth', 'token', 'id') if token_id: token = identity.token_id_driver().token_from_id(token_id) token_driver = identity.token_driver() token_driver.validate_token(token) username = token_driver.username(token) credential = token_driver.credential(token) def assert_tenant(user): tenant = lookup(creds, 'auth', 'tenantId') or lookup( creds, 'auth', 'tenantName') if tenant and str(user['accountId']) != tenant: raise Unauthorized('Invalid username, password or tenant id') # If the 'password' is the right length, treat it as an API api_key if len(credential) == 64: client = Client(username=username, api_key=credential, endpoint_url=cfg.CONF['softlayer']['endpoint'], proxy=cfg.CONF['softlayer']['proxy']) user = client['Account'].getCurrentUser(mask=USER_MASK) assert_tenant(user) return { 'user': user, 'credential': credential, 'auth_type': 'api_key' } else: client = Client(endpoint_url=cfg.CONF['softlayer']['endpoint'], proxy=cfg.CONF['softlayer']['proxy']) client.auth = None try: userId, tokenHash = client.\ authenticate_with_password(username, credential) user = client['Account'].getCurrentUser(mask=USER_MASK) assert_tenant(user) return { 'user': user, 'credential': tokenHash, 'auth_type': 'token' } except SoftLayerAPIError as e: if (e.faultCode == "SoftLayer_Exception_User_Customer" "_LoginFailed"): raise Unauthorized(e.faultString) raise
def __init__(self, config, client=None): self.config = config if client is None: client = Client(auth=self.config['auth'], endpoint_url=self.config['endpoint_url']) self.client = client self.ssh = SshKeyManager(client) self.instances = CCIManager(client)
def hook_get_client(req, resp, kwargs): client = Client(endpoint_url=cfg.CONF['softlayer']['endpoint']) client.auth = None req.env['tenant_id'] = None if req.headers.get('X-AUTH-TOKEN'): if 'X-AUTH-TOKEN' in req.headers: tenant_id = kwargs.get('tenant_id', req.headers.get('X-AUTH-PROJECT-ID')) token_details = get_token_details(req.headers['X-AUTH-TOKEN'], tenant_id=tenant_id) client.auth = get_auth(token_details) req.env['tenant_id'] = token_details['tenant_id'] req.env['sl_client'] = client
def get_client(): if not hasattr(g, 'client'): if session.get('sl_user_id'): auth = TokenAuthentication(session['sl_user_id'], session['sl_user_hash']) if auth: g.client = Client(auth=auth) return g.client
def authenticate_with_password(username, password, question_id=None, answer=None): client = Client() try: (user_id, user_hash) = client.authenticate_with_password(username, password, question_id, answer) session['sl_user_id'] = user_id session['sl_user_hash'] = user_hash except SoftLayerAPIError as e: c = 'SoftLayer_Exception_User_Customer_InvalidSecurityQuestionAnswer' if e.faultCode == c: return 'security_question' return False return True
def authenticate_with_password(username, password, question_id=None, answer=None): client = Client() try: (user_id, user_hash) = client.authenticate_with_password( username, password, question_id, answer) session['sl_user_id'] = user_id session['sl_user_hash'] = user_hash except SoftLayerAPIError as e: c = 'SoftLayer_Exception_User_Customer_InvalidSecurityQuestionAnswer' if e.faultCode == c: return 'security_question' return False return True
def get_api_key(username, secret, endpoint_url=None): """ Tries API-Key and password auth to get (and potentially generate) an API key. """ # Try to use a client with username/api key try: client = Client(username=username, api_key=secret, endpoint_url=endpoint_url, timeout=5) client["Account"].getCurrentUser() return secret except SoftLayerAPIError as ex: if "invalid api token" not in ex.faultString.lower(): raise # Try to use a client with username/password client = Client(endpoint_url=endpoint_url, timeout=5) client.authenticate_with_password(username, secret) user_record = client["Account"].getCurrentUser(mask="id, apiAuthenticationKeys") api_keys = user_record["apiAuthenticationKeys"] if len(api_keys) == 0: return client["User_Customer"].addApiAuthenticationKey(id=user_record["id"]) return api_keys[0]["authenticationKey"]
def authenticate(self, creds): username = lookup(creds, "auth", "passwordCredentials", "username") credential = lookup(creds, "auth", "passwordCredentials", "password") token_id = lookup(creds, "auth", "token", "id") if token_id: token = identity.token_id_driver().token_from_id(token_id) token_driver = identity.token_driver() token_driver.validate_token(token) username = token_driver.username(token) credential = token_driver.credential(token) def assert_tenant(user): tenant = lookup(creds, "auth", "tenantId") or lookup(creds, "auth", "tenantName") if tenant and str(user["accountId"]) != tenant: raise Unauthorized("Invalid username, password or tenant id") # If the 'password' is the right length, treat it as an API api_key if len(credential) == 64: client = Client( username=username, api_key=credential, endpoint_url=cfg.CONF["softlayer"]["endpoint"], proxy=cfg.CONF["softlayer"]["proxy"], ) user = client["Account"].getCurrentUser(mask=USER_MASK) assert_tenant(user) return {"user": user, "credential": credential, "auth_type": "api_key"} else: client = Client(endpoint_url=cfg.CONF["softlayer"]["endpoint"], proxy=cfg.CONF["softlayer"]["proxy"]) client.auth = None try: userId, tokenHash = client.authenticate_with_password(username, credential) user = client["Account"].getCurrentUser(mask=USER_MASK) assert_tenant(user) return {"user": user, "credential": tokenHash, "auth_type": "token"} except SoftLayerAPIError as e: if e.faultCode == "SoftLayer_Exception_User_Customer" "_LoginFailed": raise Unauthorized(e.faultString) raise
def get_new_token_v3(credentials): credential = lookup(credentials, 'auth', 'identity', 'password', 'user', 'password') username = lookup(credentials, 'auth', 'identity', 'password', 'user', 'name') def assert_tenant(user): tenant = lookup(credentials, 'auth', 'tenantId') if tenant and str(user['accountId']) != tenant: raise Unauthorized('Invalid username, password or tenant id') # If the 'password' is the right length, treat it as an API api_key if len(credential) == 64: client = Client(username=username, api_key=credential) user = client['Account'].getCurrentUser(mask=USER_MASK) assert_tenant(user) return { 'username': username, 'api_key': credential, 'auth_type': 'api_key', 'tenant_id': str(user['accountId']), 'expires': time.time() + (60 * 60 * 24) }, user else: client = Client() client.auth = None try: userId, tokenHash = client.authenticate_with_password( username, credential) user = client['Account'].getCurrentUser(mask=USER_MASK) assert_tenant(user) return { 'userId': userId, 'tokenHash': tokenHash, 'auth_type': 'token', 'tenant_id': str(user['accountId']), 'expires': time.time() + (60 * 60 * 24) }, user except SoftLayerAPIError as e: if e.faultCode == 'SoftLayer_Exception_User_Customer_LoginFailed': raise Unauthorized(e.faultString) raise
username = '' apiKey = '' if (args.username != ''): username = args.username apiKey = args.apiKey else: username = os.environ.get('SOFTLAYER_USERNAME', '') apiKey = os.environ.get('SOFTLAYER_APIKEY', '') if (username == '' or apiKey == ''): print 'Please specify a username and apiKey\n' else: endpoint_url = SoftLayer.API_PUBLIC_ENDPOINT client = Client(username=username, api_key=apiKey, endpoint_url=endpoint_url) startTime = datetime.now() results = {} if (args.action == 'LIST'): print 'Listing servers...' getInstances(args.tag) elif (args.action == 'CREATE'): print 'Creating servers...' provisionServers() elif (args.action == 'LIST_IMAGES'): print 'Listing servers...' listImages() elif (args.action == 'CAPTURE'):
parser.add_option("-v", "--primary-disk", dest="primary_disk", default=100) parser.add_option("-z", "--disks", dest="custom_disk", default=None) parser.add_option("-n", "--network", dest="network", default='1Gb') parser.add_option("-q", "--quantity", dest="quantity", default=1) parser.add_option("-i", "--image", dest="image", default='CentOS-7') parser.add_option("-r", "--region", dest="datacenter", default='sao01') parser.add_option("-l", "--local-only", dest="local_only", default=False) (opt, args) = parser.parse_args() sl_user = '******' sl_apikey = 'YOUR_SOFTLAYER_AKEY' image_regex = r'[a-zA-Z0-9]{8}(-[a-zA-Z0-9]{4}){3}-[a-zA-Z0-9]{12}' client = Client(username=sl_user,api_key=sl_apikey) vs = VSManager(client) def _str_to_bool(s): if s in ['True', 'true', 't', 1]: return True return False config = { 'domain': 'mydomain.com', 'cpu': int(opt.cpu), 'memory': str(opt.memory), 'network': str(opt.network), 'name': str(opt.server_name), 'billing': str(opt.billing),
def getVirtualGuestUserData(id): print 'Getting user data' userdata = client['SoftLayer_Virtual_Guest'].getUserData(id=id) jsonData = json.loads(userdata[0]['value']) #print jsonData['hostname'] #print jsonData['privateIPAddress'] print json.dumps(jsonData, sort_keys=True, indent=4) return userdata ############################################################################# ############################################################################# if (args.username != ''): client = Client(username=args.username, api_key=args.apiKey, endpoint_url=SoftLayer.API_PUBLIC_ENDPOINT) else: client = Client(endpoint_url=SoftLayer.API_PUBLIC_ENDPOINT) if (args.action == 'GET'): print 'Getting server...' getInstance(args.serverId) elif (args.action == 'GET_USERDATA'): print 'Getting server metadata...' getVirtualGuestUserData(args.serverId) elif (args.action == 'LIST'): print 'Listing servers...' getInstances(args.tag) elif (args.action == 'CREATE'): print 'Creating servers...'