Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

allows check auth exp to return false if no authenticated at all. Als… #60

Merged
merged 1 commit into from
Jul 11, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 37 additions & 16 deletions tdxlib/tdx_integration.py
Original file line number Diff line number Diff line change
Expand Up @@ -185,11 +185,11 @@ def __init__(self, filename=None):
if self.log_level:
self.logger = logging.getLogger('tdx_integration')
self.logger.setLevel(logging.getLevelName(self.log_level))
self.auth()
self.cache = {}
if not (self.auth()):
self.logger.error(f"Login Failed. Username or password in {filename} likely incorrect.")
self.clean_cache()

def auth(self):
def auth(self) -> bool:
try:
response = requests.post(
url=str(self.api_url) + '/auth',
Expand All @@ -203,7 +203,7 @@ def auth(self):
)
if response.status_code != 200:
raise tdxlib.tdx_api_exceptions.TdxApiHTTPError(" Response code: " + str(response.status_code) + " " +
response.reason + "\n" + " Returned: " + response.text)
response.reason + " " + " Returned: " + response.text)
else:
self.token = response.text
time.sleep(1)
Expand All @@ -213,22 +213,30 @@ def auth(self):
options={'verify_signature':False},
audience="https://www.teamdynamix.com/")
self.token_exp = decoded['exp']
return True

except requests.exceptions.RequestException as e:
self.logger.warning(f"Auth request Failed. Exception: {str(e)}")
return False
except tdxlib.tdx_api_exceptions.TdxApiHTTPError as e:
self.logger.error(str(e))
return False

def _check_auth_exp(self):
def _check_auth_exp(self) -> bool:
"""
Internal method to check the expiration of the stored access token.
If it is expired, call auth() to get a new token.
"""
# If token is expired or will expire in the next minute, get new token
if self.token_exp and self.token_exp < time.time() + 60:
self.logger.info(f"Token expires at {str(datetime.datetime.utcfromtimestamp(self.token_exp))}. "
f"Getting new token...")
self.auth()
if self.token_exp:
if self.token_exp < time.time() + 60:
self.logger.info(f"Token expires at {str(datetime.datetime.utcfromtimestamp(self.token_exp))}. "
f"Getting new token...")
return self.auth()
else:
return True
else:
return self.auth()

def _rate_limit(self, skew_mitigation_secs=5):
"""
Expand Down Expand Up @@ -259,12 +267,14 @@ def make_get(self, request_url: str, retries: int = 3):

"""
self._rate_limit()
self._check_auth_exp()
get_url = self.api_url + request_url
response = None
attempts = 0
while attempts < retries:
try:
if not (self._check_auth_exp()):
raise tdxlib.tdx_api_exceptions.TdxApiHTTPError(
f"Login Failed. Username or password in config likely incorrect.")
response = requests.get(
url=get_url,
headers={
Expand All @@ -274,7 +284,7 @@ def make_get(self, request_url: str, retries: int = 3):
)
if response.status_code != 200:
err_string = " Response code: " + str(response.status_code) + \
" " + response.reason + "\n" + " Returned: " + response.text
" " + response.reason + " " + " Returned: " + response.text
raise tdxlib.tdx_api_exceptions.TdxApiHTTPError(err_string)
val = response.json()
self.cache['rate_limit']['remaining'] = int(response.headers['X-RateLimit-Remaining'])
Expand Down Expand Up @@ -305,10 +315,12 @@ def make_post(self, request_url: str, body: dict):

"""
self._rate_limit()
self._check_auth_exp()
post_url = self.api_url + request_url
response = None
try:
if not (self._check_auth_exp()):
raise tdxlib.tdx_api_exceptions.TdxApiHTTPError(
f"Login Failed. Username or password in config likely incorrect.")
response = requests.post(
url=post_url,
headers={
Expand Down Expand Up @@ -351,14 +363,16 @@ def make_file_post(self, request_url: str, file: BinaryIO, filename: str = None)
:return: the API's response as a python dict
"""
self._rate_limit()
self._check_auth_exp()
post_url = self.api_url + request_url
response = None
if filename:
files = {'file': (filename, file)}
else:
files = {'file': file}
try:
if not (self._check_auth_exp()):
raise tdxlib.tdx_api_exceptions.TdxApiHTTPError(
f"Login Failed. Username or password in config likely incorrect.")
response = requests.post(
url=post_url,
headers={
Expand Down Expand Up @@ -397,10 +411,12 @@ def make_put(self, request_url: str, body: dict):

"""
self._rate_limit()
self._check_auth_exp()
put_url = self.api_url + request_url
response = None
try:
if not (self._check_auth_exp()):
raise tdxlib.tdx_api_exceptions.TdxApiHTTPError(
f"Login Failed. Username or password in config likely incorrect.")
response = requests.put(
url=put_url,
headers={
Expand Down Expand Up @@ -437,9 +453,12 @@ def make_delete(self, request_url: str):

"""
self._rate_limit()
self._check_auth_exp()

delete_url = self.api_url + request_url
try:
if not (self._check_auth_exp()):
raise tdxlib.tdx_api_exceptions.TdxApiHTTPError(
f"Login Failed. Username or password in config likely incorrect.")
response = requests.delete(
url=delete_url,
headers={
Expand Down Expand Up @@ -473,10 +492,12 @@ def make_patch(self, request_url: str, body: list):

"""
self._rate_limit()
self._check_auth_exp()
patch_url = self.api_url + request_url
response = None
try:
if not (self._check_auth_exp()):
raise tdxlib.tdx_api_exceptions.TdxApiHTTPError(
f"Login Failed. Username or password in config likely incorrect.")
response = requests.patch(
url=patch_url,
headers={
Expand Down
3 changes: 3 additions & 0 deletions testing/tdx_integration_testing.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import time
import unittest
import json
from datetime import datetime as dt
Expand All @@ -23,6 +24,7 @@ def setUp(self):
def test_authentication(self):
if not self.tdx:
self.setUp()
self.assertIsNotNone(self.tdx.token)
self.assertGreater(len(self.tdx.token), 200)

def test_check_auth_exp(self):
Expand Down Expand Up @@ -238,6 +240,7 @@ def test_create_room(self):
name = 'Testing Room ' + TdxTesting.timestamp
description = 'Testing room Description'
new_room = self.tdx.create_room(location, name, description=description)
time.sleep(2)
test_room = self.tdx.get_room_by_name(location, name)
self.assertEqual(new_room['Name'], test_room['Name'])

Expand Down