diff --git a/src/widgets/homebridge/proxy.js b/src/widgets/homebridge/proxy.js index d154cd43f..b05b475c2 100644 --- a/src/widgets/homebridge/proxy.js +++ b/src/widgets/homebridge/proxy.js @@ -22,11 +22,15 @@ async function login(widget) { headers, }); - const dataParsed = JSON.parse(data.toString()) - - cache.put(sessionTokenCacheKey, dataParsed.access_token); - - return { status, contentType, data: dataParsed, responseHeaders }; + try { + const { access_token, expires_in } = JSON.parse(data.toString()); + + cache.put(sessionTokenCacheKey, access_token, (expires_in * 1000) - 5 * 60 * 1000); // expires_in (s) - 5m + return { access_token }; + } catch (e) { + logger.error("Unable to login to Homebridge API: %s", e); + return { access_token: false }; + } } async function apiCall(widget, endpoint) { @@ -44,9 +48,9 @@ async function apiCall(widget, endpoint) { }); if (status === 401) { - logger.debug("Homebridge is rejecting the request, but obtaining new session token"); - const { data: loginData } = login(widget); - headers.Authorization = loginData?.auth_token; + logger.debug("Homebridge API rejected the request, attempting to obtain new session token"); + const { access_token } = login(widget); + headers.Authorization = `Bearer ${access_token}`; // retry the request, now with the new session token [status, contentType, data, responseHeaders] = await httpProxy(url, {