Skip to content

Commit

Permalink
Better token expiration handling
Browse files Browse the repository at this point in the history
  • Loading branch information
MikeBishop committed May 9, 2024
1 parent 2a6a914 commit b63a1c8
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 4 deletions.
3 changes: 0 additions & 3 deletions lib/TWCManager/Control/HTTPControl.py
Original file line number Diff line number Diff line change
Expand Up @@ -1265,11 +1265,8 @@ def process_save_settings(self, page="settings"):
carapi = master.getModuleByName("TeslaAPI")
if key == "carApiBearerToken":
carapi.setCarApiBearerToken(self.getFieldValue(key))
# New tokens expire after 8 hours
carapi.setCarApiTokenExpireTime(time.time() + 8 * 60 * 60)
elif key == "carApiRefreshToken":
carapi.setCarApiRefreshToken(self.getFieldValue(key))
carapi.setCarApiTokenExpireTime(time.time() + 45 * 24 * 60 * 60)

else:
# Write setting to dictionary
Expand Down
18 changes: 17 additions & 1 deletion lib/TWCManager/Vehicle/TeslaAPI.py
Original file line number Diff line number Diff line change
Expand Up @@ -1129,9 +1129,16 @@ def setCarApiBearerToken(self, token=None):
self.baseURL = self.regionURL["OwnerAPI"]
elif decoded.get("ou_code", "") in self.regionURL:
self.baseURL = self.regionURL[decoded["ou_code"]]

if "exp" in decoded:
self.setCarApiTokenExpireTime(int(decoded["exp"]))
else:
self.setCarApiTokenExpireTime(time.time() + 8 * 60 * 60)

except jwt.exceptions.DecodeError:
# Fallback to owner-api if we get an exception decoding jwt token
self.baseURL = self.regionURL["OwnerAPI"]
self.setCarApiTokenExpireTime(time.time() + 8 * 60 * 60)
return True
else:
return False
Expand Down Expand Up @@ -1230,6 +1237,10 @@ def wakeVehicle(self, vehicle):
logger.log(logging.INFO8, "Car API cmd wake_up" + str(req))
apiResponseDict = json.loads(req.text)
except requests.exceptions.RequestException:
if req.status_code == 401 and "expired" in req.text:
# If the token is expired, refresh it and try again
self.apiRefresh()
return self.wakeVehicle(vehicle)
return False
except json.decoder.JSONDecodeError:
return False
Expand Down Expand Up @@ -1393,7 +1404,12 @@ def get_car_api(self, url, checkReady=True, provesOnline=True):
# This one is somewhat common:
# {'response': None, 'error': 'vehicle unavailable: {:error=>"vehicle unavailable:"}', 'error_description': ''}
except requests.exceptions.RequestException:
pass
if req.status_code == 401 and "expired" in req.text:
# If the token is expired, refresh it and try again
self.apiRefresh()
continue
else:
pass
except json.decoder.JSONDecodeError:
pass

Expand Down

0 comments on commit b63a1c8

Please sign in to comment.