diff --git a/javascript/src/iframe/viamapi-iframe.js b/javascript/src/iframe/viamapi-iframe.js index c66eb9c145498d78e471533db1aeac3806757e7b..2c7de95a5eb47082ff97299dc5b245132174fb73 100644 --- a/javascript/src/iframe/viamapi-iframe.js +++ b/javascript/src/iframe/viamapi-iframe.js @@ -710,25 +710,37 @@ const connection = Penpal.connectToParent({ }); }, logout: async () => { - const authenticationPublicKey = localStorage.getItem("authenticatedIdentity"); - if (!authenticationPublicKey || !window.loadedIdentities[authenticationPublicKey]) { + try { + const authenticationPublicKey = localStorage.getItem("authenticatedIdentity"); + if (!authenticationPublicKey || !window.loadedIdentities[authenticationPublicKey]) { + return { + data: "", + code: "400", + status: "Identity not loaded" + }; + } + + // Clone headers to be able destroy authentication first. + // We need it because clients should be able reload page right after logout invocation and not wait until request completed + const headers = {...window.viamApi.getConfig().headers}; + + destroyAuthentication(); + + return executeRestfulFunction( + "private", + window.viamApi, + window.viamApi.identityLogout, + { + headers + } + ); + } catch (e) { return { data: "", code: "400", - status: "Identity not loaded" + status: e.message }; } - - const identityLogoutResponse = await executeRestfulFunction( - "private", - window.viamApi, - window.viamApi.identityLogout, - null - ); - - destroyAuthentication(); - - return identityLogoutResponse; }, identityRestoreAccess(restoreAccessIdentity, identificator) { return new Penpal.Promise(result => { @@ -1298,80 +1310,23 @@ connection.promise.then(parent => { } }, 50); - setInterval(async () => { - if (window.currentlyLoadedIdentity && !anynomousDeviceKeyEventsProcessing && !window.currentlyAuthenticatedIdentity) { - anynomousDeviceKeyEventsProcessing = true; - try { - const executeResult = await executeRestfulFunction("public", viamAnonymousApi, viamAnonymousApi.eventGetNewEventsWithoutSession, null, "devicekey"); - if(executeResult.code === "200") { - const eventsLen = executeResult.data.length; - let changedMaxDeviceKeyAnonymousEventTime = false; - for (let i = 0; i < eventsLen; i++) { - const event = executeResult.data[i]; - switch (event.type) { - case "DeviceConfirmed" : { - await setIdentityInLocalStorage(window.currentlyLoadedIdentity); - parent.onEvent(event); - break; - } - - case "QRCodeUpdated" : { - const actionID = event["actionID"]; - const QrCode = event["payloads"][1]; - - const eventCopy = JSON.parse(JSON.stringify(event)); - - QRCode.toDataURL(actionID + "," + QrCode, function (err, url) { - eventCopy["payloads"].push(url); - parent.onEvent(eventCopy); - }); - break; - } - - case "KeyDeleted" : { - const authenticationPublicKey = localStorage.getItem("authenticatedIdentity"); - clearPinCodeTtl(authenticationPublicKey); - localStorage.removeItem("uuid"); - localStorage.removeItem("token"); - localStorage.removeItem("authenticatedIdentity"); - delete window.loadedIdentities[authenticationPublicKey]; - window.currentlyLoadedIdentity = null; - window.currentlyAuthenticatedIdentity = null; - window.lastTimeGetProfile = 0; - - destroyIdentityFromLocalStorage(authenticationPublicKey); - break; - } - - default : { - parent.onEvent(event); - } + const getNewEventsWithoutSession = async () => { + anynomousDeviceKeyEventsProcessing = true; + try { + const executeResult = await executeRestfulFunction("public", viamAnonymousApi, viamAnonymousApi.eventGetNewEventsWithoutSession, null, "devicekey"); + if(executeResult.code === "200") { + const eventsLen = executeResult.data.length; + let changedMaxDeviceKeyAnonymousEventTime = false; + for (let i = 0; i < eventsLen; i++) { + const event = executeResult.data[i]; + switch (event.type) { + case "DeviceConfirmed" : { + await setIdentityInLocalStorage(window.currentlyLoadedIdentity); + parent.onEvent(event); + break; } - changedMaxDeviceKeyAnonymousEventTime = true; - maxDeviceKeyAnonymousEventTime = Math.max(maxDeviceKeyAnonymousEventTime, event.stamp); - } - - if(changedMaxDeviceKeyAnonymousEventTime) { - await executeRestfulFunction("public", viamAnonymousApi, viamAnonymousApi.eventUpdateLastViewedWithoutSession, - null, "devicekey", maxDeviceKeyAnonymousEventTime.toString()); - } - } - } catch (e) { - console.warn(e); - } - anynomousDeviceKeyEventsProcessing = false; - } - if (window.currentlyAuthenticatedIdentity != null && eventsDeviceEventsProcessing === false) { - eventsDeviceEventsProcessing = true; - try { - const executeResult = await executeRestfulFunction("private", viamApi, viamApi.eventGetNewEvents, null, "devicekey"); - if (executeResult.code === "200") { - const eventsLen = executeResult.data.length; - const changedMaxDeviceKeyEventTime = false; - for (let i = 0; i < eventsLen; i++) { - const event = executeResult.data[i]; - if (event.type === "QRCodeUpdated") { + case "QRCodeUpdated" : { const actionID = event["actionID"]; const QrCode = event["payloads"][1]; @@ -1381,59 +1336,126 @@ connection.promise.then(parent => { eventCopy["payloads"].push(url); parent.onEvent(eventCopy); }); - } else { + break; + } + + case "KeyDeleted" : { + const authenticationPublicKey = localStorage.getItem("authenticatedIdentity"); + clearPinCodeTtl(authenticationPublicKey); + localStorage.removeItem("uuid"); + localStorage.removeItem("token"); + localStorage.removeItem("authenticatedIdentity"); + delete window.loadedIdentities[authenticationPublicKey]; + window.currentlyLoadedIdentity = null; + window.currentlyAuthenticatedIdentity = null; + window.lastTimeGetProfile = 0; + + destroyIdentityFromLocalStorage(authenticationPublicKey); + break; + } + + default : { parent.onEvent(event); } - maxDeviceKeyEventTime = Math.max(maxDeviceKeyEventTime, event.stamp); } - if(changedMaxDeviceKeyEventTime) { - await executeRestfulFunction("private", viamApi, viamApi.eventUpdateLastViewed, null, "devicekey", - maxDeviceKeyEventTime.toString()); + changedMaxDeviceKeyAnonymousEventTime = true; + maxDeviceKeyAnonymousEventTime = Math.max(maxDeviceKeyAnonymousEventTime, event.stamp); + } + + if(changedMaxDeviceKeyAnonymousEventTime) { + await executeRestfulFunction("public", viamAnonymousApi, viamAnonymousApi.eventUpdateLastViewedWithoutSession, + null, "devicekey", maxDeviceKeyAnonymousEventTime.toString()); + } + } + } catch (e) { + console.warn(e); + } + anynomousDeviceKeyEventsProcessing = false; + }; + + const getNewDeviceEvents = async () => { + eventsDeviceEventsProcessing = true; + try { + const executeResult = await executeRestfulFunction("private", viamApi, viamApi.eventGetNewEvents, null, "devicekey"); + if (executeResult.code === "200") { + const eventsLen = executeResult.data.length; + const changedMaxDeviceKeyEventTime = false; + for (let i = 0; i < eventsLen; i++) { + const event = executeResult.data[i]; + if (event.type === "QRCodeUpdated") { + const actionID = event["actionID"]; + const QrCode = event["payloads"][1]; + + const eventCopy = JSON.parse(JSON.stringify(event)); + + QRCode.toDataURL(actionID + "," + QrCode, function (err, url) { + eventCopy["payloads"].push(url); + parent.onEvent(eventCopy); + }); + } else { + parent.onEvent(event); } + maxDeviceKeyEventTime = Math.max(maxDeviceKeyEventTime, event.stamp); + } + if(changedMaxDeviceKeyEventTime) { + await executeRestfulFunction("private", viamApi, viamApi.eventUpdateLastViewed, null, "devicekey", + maxDeviceKeyEventTime.toString()); } - } catch (e) { - console.warn(e); } - eventsDeviceEventsProcessing = false; + } catch (e) { + console.warn(e); } + eventsDeviceEventsProcessing = false; + }; - if (window.currentlyAuthenticatedIdentity != null && eventsEntityEventsProcessing === false) { - eventsEntityEventsProcessing = true; - try { - const executeResult = await executeRestfulFunction("private", viamApi, viamApi.eventGetNewEvents, null, "entity"); - - if (executeResult.code === "200") { - const eventsLen = executeResult.data.length; - let changedMaxEntityEventTime = false; - for (let i = 0; i < eventsLen; i++) { - const event = executeResult.data[i]; - if (event.type === "QRCodeUpdated") { - const actionID = event["actionID"]; - const QrCode = event["payloads"][1]; + const getNewEntityEvents = async () => { + eventsEntityEventsProcessing = true; + try { + const executeResult = await executeRestfulFunction("private", viamApi, viamApi.eventGetNewEvents, null, "entity"); - const eventCopy = JSON.parse(JSON.stringify(event)); + if (executeResult.code === "200") { + const eventsLen = executeResult.data.length; + let changedMaxEntityEventTime = false; + for (let i = 0; i < eventsLen; i++) { + const event = executeResult.data[i]; + if (event.type === "QRCodeUpdated") { + const actionID = event["actionID"]; + const QrCode = event["payloads"][1]; - QRCode.toDataURL(actionID + "," + QrCode, function (err, url) { - eventCopy["payloads"].push(url); - parent.onEvent(eventCopy); - }); + const eventCopy = JSON.parse(JSON.stringify(event)); - continue; - } + QRCode.toDataURL(actionID + "," + QrCode, function (err, url) { + eventCopy["payloads"].push(url); + parent.onEvent(eventCopy); + }); - parent.onEvent(event); - changedMaxEntityEventTime = true; - maxEntityEventTime = Math.max(maxEntityEventTime, event.stamp); - } - if(changedMaxEntityEventTime) { - await executeRestfulFunction("private", viamApi, viamApi.eventUpdateLastViewed, null, "entity", - maxEntityEventTime.toString()); + continue; } + + parent.onEvent(event); + changedMaxEntityEventTime = true; + maxEntityEventTime = Math.max(maxEntityEventTime, event.stamp); + } + if(changedMaxEntityEventTime) { + await executeRestfulFunction("private", viamApi, viamApi.eventUpdateLastViewed, null, "entity", + maxEntityEventTime.toString()); } - } catch (e) { - console.warn(e); } - eventsEntityEventsProcessing = false; + } catch (e) { + console.warn(e); + } + eventsEntityEventsProcessing = false; + } + + setInterval(() => { + if (window.currentlyLoadedIdentity && !anynomousDeviceKeyEventsProcessing && !window.currentlyAuthenticatedIdentity) { + getNewEventsWithoutSession(); + } + + if (window.currentlyAuthenticatedIdentity) { + // These functions has to be executed at the same time. + !eventsDeviceEventsProcessing && getNewDeviceEvents(); + !eventsEntityEventsProcessing && getNewEntityEvents(); } }, 1000); }); diff --git a/main.go b/main.go index af0efbcb69289482212e8fffe26c674d9a2f1c2a..6d931629ef40a58c49882b40be4f203a03e4dd4f 100644 --- a/main.go +++ b/main.go @@ -38,9 +38,17 @@ func buildPenpalMethods() string { prefixes := []string{} endPoints := server.GetEndPoints(prefixes) - result := - "import Penpal from 'penpal';\n\n" + - "export default {\n" + result := ` +const encodeResponse = (code, data, status) => { + return { + code, + data, + status + }; +}; + +export default { +` methods := generatePenpalRemoteMethods(endPoints) @@ -590,31 +598,13 @@ func generatePenpalRemoteMethods(endPoints map[string]*server.EndPoint) string { privateCheckSnippet := ` const authenticationPublicKey = localStorage.getItem("authenticatedIdentity"); - if (authenticationPublicKey === null) { - result({ - "data" : "", - "code" : "400", - "status" : "Identity not authenticated" - }); - } - - if (loadedIdentities[authenticationPublicKey] === null) { - result({ - "data" : "", - "code" : "400", - "status" : "Identity not authenticated" - }); - } - - const success = extendPinCodeTtl(authenticationPublicKey); - - if(success === false) { - result({"data" : "", - "code" : "400", - "status" : "Identity not authenticated" - }) - } - + if ( + !authenticationPublicKey || + !window.loadedIdentities[authenticationPublicKey] || + !extendPinCodeTtl(authenticationPublicKey) + ) { + return encodeResponse("400", "", "Identity not authenticated"); + } ` for i := 0; i < keysLen; i++ { @@ -626,24 +616,14 @@ func generatePenpalRemoteMethods(endPoints map[string]*server.EndPoint) string { if url == "/identity/getIdentityProfileData" { privateCheckSnippet = ` - const authenticationPublicKey = localStorage.getItem("authenticatedIdentity"); - - if (authenticationPublicKey === null) { - result({ - "data" : "", - "code" : "400", - "status" : "Identity not authenticated" - }); - } - - if (loadedIdentities[authenticationPublicKey] === null) { - result({ - "data" : "", - "code" : "400", - "status" : "Identity not authenticated" - }); - } - + const authenticationPublicKey = localStorage.getItem("authenticatedIdentity"); + + if ( + !authenticationPublicKey || + !window.loadedIdentities[authenticationPublicKey] + ) { + return encodeResponse("400", "", "Identity not authenticated"); + } ` } @@ -685,12 +665,9 @@ func generatePenpalRemoteMethods(endPoints map[string]*server.EndPoint) string { lastComma = "" } - method := packageStr + strings.Title(methodStr) + ": function(" + args + ") {\n" + - " return new Penpal.Promise(function(result) {\n" + snippet + - " executeRestfulFunction(\"" + endPoints[url].HandlerType + "\", viamApi, viamApi." + packageStr + strings.Title(methodStr) + ", null" + lastComma + args + ").then(function(executeResult) {\n" + - " result(executeResult);\n" + - " });\n" + - " });\n" + + method := packageStr + strings.Title(methodStr) + ": async function(" + args + ") {\n" + + snippet + + " return await executeRestfulFunction(\"" + endPoints[url].HandlerType + "\", viamApi, viamApi." + packageStr + strings.Title(methodStr) + ", null" + lastComma + args + ");\n" + "}" methods += method @@ -713,12 +690,9 @@ func generatePenpalRemoteMethods(endPoints map[string]*server.EndPoint) string { snippet = privateCheckSnippet } - method := packageStr + strings.Title(methodStr) + ": function() {\n" + - " return new Penpal.Promise(function(result) {\n" + snippet + - " executeRestfulFunction(\"" + endPoints[url].HandlerType + "\", viamApi, viamApi." + packageStr + strings.Title(methodStr) + ", null).then(function(executeResult) {\n" + - " result(executeResult);\n" + - " });\n" + - " });\n" + + method := packageStr + strings.Title(methodStr) + ": async function() {\n" + + snippet + + " return await executeRestfulFunction(\"" + endPoints[url].HandlerType + "\", viamApi, viamApi." + packageStr + strings.Title(methodStr) + ", null);\n" + "}" methods += method