From 2ca46b595b5cf9945ec612ae03eb51c4581f343a Mon Sep 17 00:00:00 2001
From: theshaun <shaun@theshaun.com>
Date: Fri, 19 May 2023 10:41:04 +1000
Subject: [PATCH] Fix issue with key expiring and not updating correctly

---
 src/widgets/qnap/proxy.js | 13 +++++++++++--
 1 file changed, 11 insertions(+), 2 deletions(-)

diff --git a/src/widgets/qnap/proxy.js b/src/widgets/qnap/proxy.js
index 3da4c20a..489f24ac 100644
--- a/src/widgets/qnap/proxy.js
+++ b/src/widgets/qnap/proxy.js
@@ -57,8 +57,17 @@ async function apiCall(widget, endpoint, service) {
     return { status, contentType, data: null, responseHeaders };
   }
 
-  const dataDecoded = xml2json(data.toString(), { compact: true });
-  return { status, contentType, data: JSON.parse(dataDecoded.toString()), responseHeaders };
+  let dataDecoded = JSON.parse(xml2json(data.toString(), { compact: true }).toString());
+
+  if (dataDecoded.QDocRoot.authPassed._cdata === '0') {
+    logger.error("QNAP API rejected the request, attempting to obtain new session token");
+    key = await login(widget, service);
+    apiUrl = new URL(formatApiCall(`${endpoint}&sid=${key}`, widget));
+    [status, contentType, data, responseHeaders] = await httpProxy(apiUrl);
+    dataDecoded = JSON.parse(xml2json(data.toString(), { compact: true }).toString());
+  }
+
+  return { status, contentType, data: dataDecoded, responseHeaders };
 }
 
 export default async function qnapProxyHandler(req, res) {