def authenticate(self): """ Using the supplied credentials, connects to the specified authentication endpoint and attempts to log in. If successful, records the token information. """ creds = self._get_credentials() headers = { "Content-Type": "application/json", "Accept": "application/json", } resp = self.method_post("tokens", data=creds, headers=headers, std_headers=False) if resp.status_code == 401: # Invalid authorization raise exc.AuthenticationFailed("Incorrect/unauthorized " "credentials received") elif resp.status_code > 299: msg_dict = resp.json() try: msg = msg_dict[msg_dict.keys()[0]]["message"] except KeyError: msg = None if msg: err = "%s - %s." % (resp.reason, msg) else: err = "%s." % resp.reason raise exc.AuthenticationFailed(err) resp_body = resp.json() self._parse_response(resp_body) self.authenticated = True
def _call_token_auth(self, token, tenant_id, tenant_name): key = val = None if tenant_id: key = "tenantId" val = tenant_id elif tenant_name: key = "tenantName" val = tenant_name body = {"auth": { "token": {"id": token}, }} if(key and val): body["auth"][key] = val headers = {"Content-Type": "application/json", "Accept": "application/json", } resp, resp_body = self.method_post("tokens", data=body, headers=headers, std_headers=False) if resp.status_code == 401: # Invalid authorization raise exc.AuthenticationFailed("Incorrect/unauthorized " "credentials received") elif resp.status_code > 299: msg = resp_body[next(iter(resp_body))]["message"] raise exc.AuthenticationFailed("%s - %s." % (resp.reason, msg)) return resp, resp_body
def authenticate(self): """ Using the supplied credentials, connects to the specified authentication endpoint and attempts to log in. If successful, records the token information. """ self.authenticated = False creds = self._get_credentials() url = urlparse.urljoin(self.auth_endpoint, "tokens") auth_req = urllib2.Request(url, data=json.dumps(creds)) auth_req.add_header("Content-Type", "application/json") # TODO: dabo: add better error reporting try: raw_resp = urllib2.urlopen(auth_req) except urllib2.HTTPError as e: errcode = e.getcode() if errcode == 401: # Invalid authorization raise exc.AuthenticationFailed("Incorrect/unauthorized " "credentials received") else: raise exc.AuthenticationFailed("Authentication Error: %s" % e) resp = json.loads(raw_resp.read()) self._parse_response(resp) self.authenticated = True
def _call_token_auth(self, token, tenant_id, tenant_name): if not any((tenant_id, tenant_name)): raise exc.MissingAuthSettings("You must supply either the tenant " "name or tenant ID") if tenant_id: key = "tenantId" val = tenant_id else: key = "tenantName" val = tenant_name body = { "auth": { key: val, "token": { "id": token }, } } headers = { "Content-Type": "application/json", "Accept": "application/json", } resp = self.method_post("tokens", data=body, headers=headers, std_headers=False) if resp.status_code == 401: # Invalid authorization raise exc.AuthenticationFailed("Incorrect/unauthorized " "credentials received") elif resp.status_code > 299: msg_dict = resp.json() msg = msg_dict[msg_dict.keys()[0]]["message"] raise exc.AuthenticationFailed("%s - %s." % (resp.reason, msg)) return resp
def _get_access_token(self, code): r = requests.post( OAUTH_ENDPOINT + u'token/', data={ u'code': code, u'redirect_uri': self._redirect_uri, u'grant_type': u'authorization_code', }, auth=(self._client_id, self._client_secret) ) if r.status_code != 200: try: err = r.json() err[u'code'] = r.status_code except: err = {} raise exc.AuthenticationFailed(u"Unable to get oauth access token, " u"wrong client_id or client_secret ? (%s)" % str(err)) oauth_token = r.json() config = configparser.ConfigParser() config.read(TOKENS_FILE) if not config.has_section(u"hubic"): config.add_section(u"hubic") if oauth_token[u'access_token'] is not None: config.set(u"hubic", u"access_token", oauth_token[u'access_token']) with open(TOKENS_FILE, u'wb') as configfile: config.write(configfile) else: raise exc.AuthenticationFailed( u"Unable to get oauth access token, wrong client_id or client_secret ? (%s)" % str(err)) if oauth_token[u'refresh_token'] is not None: config.set(u"hubic", u"refresh_token", oauth_token[u'refresh_token']) with open(TOKENS_FILE, u'wb') as configfile: config.write(configfile) else: raise exc.AuthenticationFailed(u"Unable to get the refresh token.") # removing username and password from .hubic_tokens if config.has_option(u"hubic", u"email"): config.remove_option(u"hubic", u"email") with open(TOKENS_FILE, u'wb') as configfile: config.write(configfile) print(u"username has been removed from the .hubic_tokens file sent to the CE.") if config.has_option(u"hubic", u"password"): config.remove_option(u"hubic", u"password") with open(TOKENS_FILE, u'wb') as configfile: config.write(configfile) print(u"password has been removed from the .hubic_tokens file sent to the CE.") return oauth_token
def authenticate(self, username=None, password=None, api_key=None, tenant_id=None, connect=False): """ Using the supplied credentials, connects to the specified authentication endpoint and attempts to log in. Credentials can either be passed directly to this method, or previously-stored credentials can be used. If authentication is successful, the token and service catalog information is stored, and clients for each service and region are created. The 'connect' parameter is retained for backwards compatibility. It no longer has any effect. """ self.username = username or self.username or pyrax.get_setting( "username") # Different identity systems may pass these under inconsistent names. self.password = password or self.password or api_key or self.api_key self.api_key = api_key or self.api_key or self.password self.tenant_id = tenant_id or self.tenant_id or pyrax.get_setting( "tenant_id") creds = self._format_credentials() headers = { "Content-Type": "application/json", "Accept": "application/json", } resp, resp_body = self.method_post("tokens", data=creds, headers=headers, std_headers=False) if resp.status_code == 401: # Invalid authorization raise exc.AuthenticationFailed("Incorrect/unauthorized " "credentials received") elif 500 <= resp.status_code < 600: # Internal Server Error try: error_msg = resp_body[list(resp_body.keys())[0]]["message"] except (KeyError, AttributeError): error_msg = "Service Currently Unavailable" raise exc.InternalServerError(error_msg) elif resp.status_code > 299: try: msg = resp_body[list(resp_body.keys())[0]]["message"] except (KeyError, AttributeError): msg = None if msg: err = "%s - %s." % (resp.reason, msg) else: err = "%s." % resp.reason raise exc.AuthenticationFailed(err) self._parse_response(resp_body) self.authenticated = True
def _refresh_access_token(self): config = configparser.ConfigParser() config.read(TOKENS_FILE) refresh_token = config.get(u"hubic", u"refresh_token") if refresh_token is None: raise exc.AuthenticationFailed(u"refresh_token is null. Not acquiered before ?") success = False max_retries = 20 retries = 0 sleep_time = 30 max_sleep_time = 3600 while retries < max_retries and not success: r = requests.post( OAUTH_ENDPOINT + u'token/', data={ u'refresh_token': refresh_token, u'grant_type': u'refresh_token', }, auth=(self._client_id, self._client_secret) ) if r.status_code != 200: if r.status_code == 509: print(u"status_code 509: attempt #", retries, u" failed") retries += 1 time.sleep(sleep_time) sleep_time = sleep_time * 2 if sleep_time > max_sleep_time: sleep_time = max_sleep_time else: try: err = r.json() err[u'code'] = r.status_code except: err = {} raise exc.AuthenticationFailed( u"Unable to get oauth access token, wrong client_id or client_secret ? (%s)" % str(err)) else: success = True if not success: raise exc.AuthenticationFailed( u"All the attempts failed to get the refresh token: " u"status_code = 509: Bandwidth Limit Exceeded") oauth_token = r.json() if oauth_token[u'access_token'] is not None: return oauth_token else: raise exc.AuthenticationFailed(u"Unable to get oauth access token from json")
def authenticate(self, connect=False): if ((self.username == self._good_username) and (self.password == self._good_password)): self._parse_response(self.fake_response()) self.authenticated = True else: self.authenticated = False raise exc.AuthenticationFailed("No match for '%s'/'%s' " "username/password" % (self.username, self.password))
def authenticate(self): if ((self.username == self._good_username) and (self.api_key == self._good_api_key)): self._parse_response(self.fake_response()) self.authenticated = True else: self.authenticated = False raise exc.AuthenticationFailed( "No match for '%s'/'%s' username/api_key" % (self.username, self.api_key))
def authenticate(self): config = configparser.ConfigParser() config.read(TOKENS_FILE) if config.has_option(u"hubic", u"refresh_token"): oauth_token = self._refresh_access_token() else: r = requests.get( OAUTH_ENDPOINT + u'auth/?client_id={0}&redirect_uri={1}' u'&scope=credentials.r,account.r&response_type=code&state={2}'.format( quote(self._client_id), quote_plus(self._redirect_uri), pyrax.utils.random_ascii() # csrf ? wut ?.. ), allow_redirects=False ) if r.status_code != 200: raise exc.AuthenticationFailed(u"Incorrect/unauthorized " u"client_id (%s)" % str(self._parse_error(r))) try: from lxml import html as lxml_html except ImportError: lxml_html = None if lxml_html: oauth = lxml_html.document_fromstring(r.content).xpath(u'//input[@name="oauth"]') oauth = oauth[0].value if oauth else None else: oauth = re.search( r'<input\s+[^>]*name=[\'"]?oauth[\'"]?\s+[^>]*value=[\'"]?(\d+)[\'"]?>', r.content) oauth = oauth.group(1) if oauth else None if not oauth: raise exc.AuthenticationFailed(u"Unable to get oauth_id from authorization page") if self._email is None or self._password is None: raise exc.AuthenticationFailed(u"Cannot retrieve email and/or password. " u"Please run expresslane-hubic-setup.sh") r = requests.post( OAUTH_ENDPOINT + u'auth/', data={ u'action': u'accepted', u'oauth': oauth, u'login': self._email, u'user_pwd': self._password, u'account': u'r', u'credentials': u'r', }, allow_redirects=False ) try: query = urllib.parse.urlsplit(r.headers[u'location']).query code = dict(urllib.parse.parse_qsl(query))[u'code'] except: raise exc.AuthenticationFailed(u"Unable to authorize client_id, " u"invalid login/password ?") oauth_token = self._get_access_token(code) if oauth_token[u'token_type'].lower() != u'bearer': raise exc.AuthenticationFailed(u"Unsupported access token type") r = requests.get( API_ENDPOINT + u'account/credentials', auth=BearerTokenAuth(oauth_token[u'access_token']), ) swift_token = r.json() self.authenticated = True self.token = swift_token[u'token'] self.expires = swift_token[u'expires'] self.services[u'object_store'] = Service(self, { u'name': u'HubiC', u'type': u'cloudfiles', u'endpoints': [ {u'public_url': swift_token[u'endpoint']} ] }) self.username = self.password = None
def authenticate(self): # import httplib # httplib.HTTPConnection.debuglevel = 1 r = requests.get( OAUTH_ENDPOINT+'auth/?client_id={0}&redirect_uri={1}' '&scope=credentials.r,account.r&response_type=code&state={2}'.format( quote(self._client_id), quote_plus(self._redirect_uri), pyrax.utils.random_ascii() # csrf ? wut ?.. ), allow_redirects=False ) if r.status_code != 200: raise exc.AuthenticationFailed("Incorrect/unauthorized " "client_id (%s)"%str(self._parse_error(r))) try: from lxml import html as lxml_html except ImportError: lxml_html = None if lxml_html: oauth = lxml_html.document_fromstring(r.content).xpath('//input[@name="oauth"]') oauth = oauth[0].value if oauth else None else: oauth = re.search(r'<input\s+[^>]*name=[\'"]?oauth[\'"]?\s+[^>]*value=[\'"]?(\d+)[\'"]?>', r.content) oauth = oauth.group(1) if oauth else None if not oauth: raise exc.AuthenticationFailed("Unable to get oauth_id from authorization page") r = requests.post( OAUTH_ENDPOINT+'auth/', data = { 'action': 'accepted', 'oauth': oauth, 'login': self._email, 'user_pwd': self._password, 'account': 'r', 'credentials': 'r', }, allow_redirects=False ) if r.status_code == 302 and r.headers['location'].startswith(self._redirect_uri): query = urlparse.urlsplit(r.headers['location']).query code = dict(urlparse.parse_qsl(query))['code'] else: raise exc.AuthenticationFailed("Unable to authorize client_id, invalid login/password ?") r = requests.post( OAUTH_ENDPOINT+'token/', data={ 'code': code, 'redirect_uri': self._redirect_uri, 'grant_type': 'authorization_code', }, auth=(self._client_id, self._client_secret) ) if r.status_code != 200: try: err = r.json() err['code'] = r.status_code except: err = {} raise exc.AuthenticationFailed("Unable to get oauth access token, " "wrong client_id or client_secret ? (%s)"%str(err)) oauth_token = r.json() if oauth_token['token_type'].lower() != 'bearer': raise exc.AuthenticationFailed("Unsupported access token type") r = requests.get( API_ENDPOINT+'account/credentials', auth=BearerTokenAuth(oauth_token['access_token']), ) swift_token = r.json() self.authenticated = True self.token = swift_token['token'] self.expires = swift_token['expires'] self.services['object_store'] = Service(self, { 'name': 'HubiC', 'type': 'cloudfiles', 'endpoints': [ {'public_url': swift_token['endpoint']} ] }) self.username = self.password = None