Skip to content

Commit

Permalink
[fix] Relog in when not authenticated error.
Browse files Browse the repository at this point in the history
Related Github issues: #86
  • Loading branch information
vlebourl committed Jul 2, 2020
1 parent 992e315 commit 4cdcd23
Showing 1 changed file with 61 additions and 5 deletions.
66 changes: 61 additions & 5 deletions custom_components/tahoma/tahoma_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,61 @@ def __init__(self, userName, userPassword, **kwargs):
self.__setup = None
self.login()

def is_authenticated(self):
"""Return True if the user is authenticated."""
request = requests.get(
BASE_URL + "authenticated",
headers={"User-Agent": "mine", "Cookie": self.__cookie},
timeout=10,
)
if request.status_code == 200:
try:
result = request.json()
except ValueError as error:
raise Exception("Not a valid result, protocol error: " + str(error))
return result["authenticated"]
else:
raise Exception(
"Could not check authenticated: " + str(request.status_code)
)

def logout(self):
"""Logout from TaHoma API."""
if not self.__logged_in:
return True
request = requests.post(
BASE_URL + "logout",
headers={"User-Agent": "mine", "Cookie": self.__cookie},
timeout=10,
)
try:
result = request.json()
except ValueError as error:
raise Exception(
"Not a valid result for logout, "
+ "protocol error: "
+ request.status_code
+ " - "
+ request.reason
+ "("
+ error
+ ")"
)

if "error" in result.keys():
raise Exception("Could not logout: " + result["error"])

if request.status_code != 200:
raise Exception(
"Could not login, HTTP code: "
+ str(request.status_code)
+ " - "
+ request.reason
)

self.__logged_in = False
return True

def login(self):
"""Login to TaHoma API."""
if self.__logged_in:
Expand Down Expand Up @@ -82,7 +137,7 @@ def login(self):
raise Exception("Could not login, no cookie set")

self.__cookie = cookie
self.__logged_in = True
self.__logged_in = self.is_authenticated()
return self.__logged_in

def send_request(
Expand All @@ -98,8 +153,11 @@ def send_request(
:param retries: Maximum number of retries.
:return:
"""
if not self.__logged_in:
self.login()
if not self.is_authenticated():
if not self.login():
raise Exception("Could not get authenticated")
headers["Cookie"] = self.__cookie
self.send_request(method, url, headers, data, timeout, retries)

stack = pprint.pformat(traceback.extract_stack())
if "asyncio" in stack:
Expand All @@ -117,8 +175,6 @@ def send_request(
+ request.text
)
else:
if "Not authenticated" in request.text:
self.__logged_in = False
self.send_request(method, url, headers, data, timeout, retries - 1)

def get_user(self):
Expand Down

0 comments on commit 4cdcd23

Please sign in to comment.