diff --git a/javascript/src/iframe/viamapi-iframe.js b/javascript/src/iframe/viamapi-iframe.js
index 25e867db8d1b3004d719e3a18be753728bb4384f..443640ff94bd8b932037770ca3d53a4d1ceef6db 100644
--- a/javascript/src/iframe/viamapi-iframe.js
+++ b/javascript/src/iframe/viamapi-iframe.js
@@ -1,3 +1,5 @@
+import {createDeviceHash} from '../utilities/appUtility';
+
 const libmime = require('libmime');
 const QRCode = require('qrcode');
 const pkijs = require('pkijs');
@@ -44,13 +46,13 @@ const OID_PKCS7_EnvelopedData       = "1.2.840.113549.1.7.3";
 const OID_PKCS9_EmailAddress        = "1.2.840.113549.1.9.1";
 const OID_PKCS9_ContentType         = "1.2.840.113549.1.9.3";
 const OID_PKCS9_MessageDigest       = "1.2.840.113549.1.9.4";
-const OID_PKCS9_SigningTime         = "1.2.840.113549.1.9.5"
+const OID_PKCS9_SigningTime         = "1.2.840.113549.1.9.5";
 
 const defaultAlgorithms = {
   hashAlg: "SHA-256",
   signAlg: "RSASSA-PKCS1-v1_5",
   keyLength: 2048
-}
+};
 
 const AES_encryptionVariant_Password  = 2;
 const encryptionAlgorithm = {
@@ -173,7 +175,7 @@ function createCertificate(certData, issuerData = null)
 
     const serialNumberBuffer = new ArrayBuffer(20);
     const serialNumberView = new Uint8Array(serialNumberBuffer);
-    pkijs.getRandomValues(serialNumberView)
+    pkijs.getRandomValues(serialNumberView);
     // noinspection JSUnresolvedFunction
     certificate.serialNumber = new asn1js.Integer({ valueHex: serialNumberView });
     //endregion Put a static values
@@ -460,7 +462,7 @@ function createCertificate(certData, issuerData = null)
       publicKeyPEM: encodePEM(publicKeyBuffer, "PUBLIC KEY"),
       privateKey: privateKey,
       privateKeyPEM: encodePEM(privateKeyBuffer, "PRIVATE KEY")
-    }
+    };
     return result;
   });
 }
@@ -469,10 +471,10 @@ function formatPEM(pemString) {
   const lineWidth = 64;
   let resultString = "";
   let start = 0;
-  let piece = "";
-  while ( (piece = pemString.substring(start, start + lineWidth)).length > 0 ) {
+  let piece;
+  while ((piece = pemString.substring(start, start + lineWidth)).length > 0) {
     start += lineWidth;
-    resultString += piece + '\r\n'
+    resultString += piece + '\r\n';
   }
   return resultString;
 }
@@ -597,14 +599,14 @@ function createPassportCertificate(commonNameArg) {
       validYears: 5 //optional, defaults to 1
     },
     isCA: true // optional flag denoting if this is CA certificate or leaf certificate, defaults to false
-  }
+  };
 
   return createCertificate(certData, null)
 }
 
 function createOneTimePassportCertificate(commonNameArg, emailArg, privateKeyIssuerArg, certicateIssuerArg) {
-  var certData = null
-  if(emailArg != null && emailArg != "") {
+  var certData = null;
+  if(emailArg != null && emailArg !== "") {
     certData = {
       algorithms: {
         hashAlg: "SHA-256",
@@ -660,7 +662,7 @@ function createOneTimePassportCertificate(commonNameArg, emailArg, privateKeyIss
     const issuerData = {
       certificate: parseCertificate(certicateIssuerArg),// vereignCACertPEM),
       privateKey: privateKeyDecoded
-    }
+    };
     return createCertificate(certData, issuerData);
     //console.log(vereignIntermediateKey)
   });
@@ -694,11 +696,11 @@ function arrayBufferToBase64(buffer) {
 const newline = /\r\n|\r|\n/g;
 
 function capitalizeFirstLetter(string) {
-  if(string == "id") {
+  if(string === "id") {
     return "ID"
   }
 
-  if(string == "mime") {
+  if(string === "mime") {
     return "MIME";
   }
 
@@ -706,31 +708,28 @@ function capitalizeFirstLetter(string) {
 }
 
 function capitalizeHeader(string) {
-  result = ""
-  tokens = string.split("-")
-  for(var i = 0; i < tokens.length; i++) {
-    result += capitalizeFirstLetter(tokens[i])
-    if(i != tokens.length - 1) {
-      result += "-"
+  let result = "";
+  const tokens = string.split("-");
+  for (let i = 0; i < tokens.length; i++) {
+    result += capitalizeFirstLetter(tokens[i]);
+    if (i !== tokens.length - 1) {
+      result += "-";
     }
   }
 
-  return result
+  return result;
 }
 
 function signEmail(mime, signingCert, certificateChain, privateKey) {
-  signingCertObj = parseCertificate(signingCert)
-  certificateChainObj = []
-  certificateChainObj[0] = parseCertificate(signingCert)
-  for(var i = 0; i < certificateChain.length; i++) {
+  const signingCertObj = parseCertificate(signingCert);
+  const certificateChainObj = [];
+  certificateChainObj[0] = parseCertificate(signingCert);
+  for (let i = 0; i < certificateChain.length; i++) {
     certificateChainObj[i + 1] = parseCertificate(certificateChain[i])
   }
-  //console.log(certificateChainObj)
 
   return parsePrivateKey(privateKey).then(privateKeyDecoded => {
-
     return signEmailObjects(mime, signingCertObj, certificateChainObj, privateKeyDecoded);
-    //console.log(vereignIntermediateKey)
   });
 }
 
@@ -776,12 +775,12 @@ Vereign - Authentic Communication
     "Content-Disposition",
     "Content-Language",
     "Content-Location"
-  ]
+  ];
 
   mime = mime.replace(newline, '\r\n');
 
-  let newHeaderLines = ""
-  let headersEnd = mime.indexOf('\r\n\r\n') //the first empty line
+  let newHeaderLines = "";
+  let headersEnd = mime.indexOf('\r\n\r\n'); //the first empty line
 
   if (headersEnd < 0 && mime.startsWith('\r\n')) {
 
@@ -790,16 +789,16 @@ Vereign - Authentic Communication
   } else
   if (headersEnd >= 0) {
 
-    let mimeHeaders = {}
-    let mimeBody = mime.substring(headersEnd + 4)
+    let mimeHeaders = {};
+    let mimeBody = mime.substring(headersEnd + 4);
 
-    let mimeHeadersStr = mime.substring(0, headersEnd)
+    let mimeHeadersStr = mime.substring(0, headersEnd);
 
-    let headers = libmime.decodeHeaders(mimeHeadersStr)
+    let headers = libmime.decodeHeaders(mimeHeadersStr);
     for (var i = 0; i < mimeHeadersTitles.length; i++) {
-      let key = mimeHeadersTitles[i].toLowerCase()
+      let key = mimeHeadersTitles[i].toLowerCase();
       if(key in headers) {
-        mimeHeaders[key] = headers[key]
+        mimeHeaders[key] = headers[key];
         delete headers[key]
       }
     }
@@ -810,7 +809,7 @@ Vereign - Authentic Communication
       }
     }
 
-    let newMimeHeaderLines = ""
+    let newMimeHeaderLines = "";
     for(let key in mimeHeaders) {
       if(!(key === "")) {
         newMimeHeaderLines += capitalizeHeader(key) + ": " + mimeHeaders[key] + '\r\n';
@@ -824,7 +823,7 @@ Vereign - Authentic Communication
     mime = newMimeHeaderLines + '\r\n' + mimeBody
   }
 
-  let dataBuffer = Buffer.from(mime,'utf-8')
+  let dataBuffer = Buffer.from(mime,'utf-8');
 
   let sequence = Promise.resolve();
 
@@ -973,12 +972,12 @@ Vereign - Authentic Communication
     (cmsSignedBuffer) =>
     {
       let signature = arrayBufferToBase64Formatted(cmsSignedBuffer);
-      let boundary = makeBoundary()
+      let boundary = makeBoundary();
 
-      template = template.replace(/{{boundary}}/g, boundary)
-      template = template.replace("{{signature}}", signature)
-      template = template.replace("{{headers}}", newHeaderLines)
-      template = template.replace("{{mime}}", mime)
+      template = template.replace(/{{boundary}}/g, boundary);
+      template = template.replace("{{signature}}", signature);
+      template = template.replace("{{headers}}", newHeaderLines);
+      template = template.replace("{{mime}}", mime);
 
       //template = template.replace(newline, '\r\n')
       return template
@@ -989,7 +988,7 @@ Vereign - Authentic Communication
 }
 
 function makeBoundary() {
-  let len = 20 + Math.random() * 20
+  let len = 20 + Math.random() * 20;
   return 'W0RyLiBEYW15YW4gTWl0ZXZd--' + makeid(len)
 }
 
@@ -1013,56 +1012,56 @@ CryptoData.prototype.set = function(obj) {
   for(var member in obj) {
     this[member] = JSON.parse(JSON.stringify(obj[member]))
   }
-}
+};
 
 CryptoData.prototype.serialize = function() {
   return JSON.stringify(this)
-}
+};
 
 CryptoData.prototype.deserialize = function(serialized) {
-  var obj = JSON.parse(serialized)
+  var obj = JSON.parse(serialized);
   this.set(obj)
-}
+};
 
 CryptoData.prototype.setPublicKey = function(publicKey) {
   this["publicKey"] = publicKey
-}
+};
 
 CryptoData.prototype.getPublicKey = function() {
   return this["publicKey"]
-}
+};
 
 CryptoData.prototype.setPrivateKey = function(privateKey) {
   this["privateKey"] = privateKey
-}
+};
 
 CryptoData.prototype.getPrivateKey = function() {
   return this["privateKey"]
-}
+};
 
 CryptoData.prototype.setx509Certificate = function(x509Certificate) {
   this["x509Certificate"] = x509Certificate
-}
+};
 
 CryptoData.prototype.getx509Certificate = function() {
   return this["x509Certificate"]
-}
+};
 
 CryptoData.prototype.setKeyUUID = function(keyUUID) {
   this["keyUUID"] = keyUUID
-}
+};
 
 CryptoData.prototype.getKeyUUID = function() {
   return this["keyUUID"]
-}
+};
 
 CryptoData.prototype.setChain = function(chain) {
   this["chain"] = chain
-}
+};
 
 CryptoData.prototype.getChain = function() {
   return this["chain"]
-}
+};
 
 function Identity() {
 }
@@ -1071,32 +1070,32 @@ Identity.prototype.set = function(obj) {
   for(var member in obj) {
     this[member] = JSON.parse(JSON.stringify(obj[member]))
   }
-}
+};
 
 Identity.prototype.serialize = function() {
   return JSON.stringify(this)
-}
+};
 
 Identity.prototype.deserialize = function(serialized) {
-  var obj = JSON.parse(serialized)
+  var obj = JSON.parse(serialized);
   this.set(obj)
-}
+};
 
 Identity.prototype.setAuthentication = function(cryptoData) {
   this["authentication"] = cryptoData
-}
+};
 
 Identity.prototype.getAuthentication = function() {
   return this["authentication"]
-}
+};
 
 Identity.prototype.setPinCode = function(pinCode) {
   this["pinCode"] = pinCode
-}
+};
 
 Identity.prototype.getPinCode = function() {
   return this["pinCode"]
-}
+};
 
 Identity.prototype.setPassport = function(passportUUID, cryptoData) {
   if(this["passports"] === undefined || this["passports"] === null) {
@@ -1104,7 +1103,7 @@ Identity.prototype.setPassport = function(passportUUID, cryptoData) {
   }
 
   this["passports"][passportUUID] = cryptoData
-}
+};
 
 Identity.prototype.getPassport = function(passportUUID) {
   if(this["passports"] === undefined || this["passports"] === null) {
@@ -1112,30 +1111,30 @@ Identity.prototype.getPassport = function(passportUUID) {
   }
 
   return this["passports"][passportUUID]
-}
+};
 
-var identityColors = ["#994392", "#cb0767", "#e51d31", "#ec671b", "#fab610"]
+var identityColors = ["#994392", "#cb0767", "#e51d31", "#ec671b", "#fab610"];
 
 function getNextColor() {
   var colorIndex = localStorage.getItem("colorIndex");
-  if (colorIndex == null || colorIndex == "") {
+  if (colorIndex == null || colorIndex === "") {
     colorIndex = 0
   }
 
-  var color = identityColors[colorIndex]
+  var color = identityColors[colorIndex];
 
   colorIndex++;
 
-  colorIndex = colorIndex % identityColors.length
+  colorIndex = colorIndex % identityColors.length;
 
-  localStorage.setItem("colorIndex", colorIndex)
+  localStorage.setItem("colorIndex", colorIndex);
 
   return color
 }
 
 function setKeyForUUID(uuid, key) {
-  var storedIdentityForUuid = localStorage.getItem("keyperuuid/" + uuid)
-  if(storedIdentityForUuid != key && storedIdentityForUuid != null && storedIdentityForUuid != "") {
+  var storedIdentityForUuid = localStorage.getItem("keyperuuid/" + uuid);
+  if(storedIdentityForUuid !== key && storedIdentityForUuid != null && storedIdentityForUuid !== "") {
     destroyIdentityFromLocalStorage(storedIdentityForUuid)
   }
 
@@ -1143,11 +1142,11 @@ function setKeyForUUID(uuid, key) {
 }
 
 function getColorForIdentity(key) {
-  var storedColor = localStorage.getItem("colors/" + key)
+  var storedColor = localStorage.getItem("colors/" + key);
 
-  if(storedColor == null || storedColor == "") {
-    storedColor = getNextColor()
-    console.log("Setting new color: " + storedColor)
+  if(storedColor == null || storedColor === "") {
+    storedColor = getNextColor();
+    console.log("Setting new color: " + storedColor);
     localStorage.setItem("colors/" + key, storedColor)
   }
 
@@ -1155,26 +1154,25 @@ function getColorForIdentity(key) {
 }
 
 function setIdentityInLocalStorage(identityToStore, extendKey = true) {
-  //console.log(getStack())
   var pinCode = identityToStore.pinCode;
   const serializedIdentity = JSON.stringify(identityToStore);
   const key = identityToStore.authentication.publicKey;
 
-  if(pinCode == null || pinCode == "") {
+  if(pinCode == null || pinCode === "") {
     pinCode = getPincode(key)
   }
 
-  if(pinCode == null || pinCode == "") {
-    console.log("Can not set identity")
+  if(pinCode == null || pinCode === "") {
+    console.log("Can not set identity");
     return null;
   }
 
   return encryptMessage(serializedIdentity, pinCode, "identity").then((encryptedIdentity) => {
-    var success = true
+    var success = true;
     if(extendKey === true) {
       success = extendPinCodeTtl(key, pinCode)
     }
-    if (success == true) {
+    if (success === true) {
       localStorage.setItem(key, encryptedIdentity);
       let serializedIdentitiesList = localStorage.getItem("identities");
       let identities = JSON.parse(serializedIdentitiesList);
@@ -1191,21 +1189,21 @@ function getProfileData(identity) {
   return new Penpal.Promise(executeResultUpper => {
     executeRestfulFunction("private", viamApi,
       viamApi.identityGetIdentityProfileData).then(executeResult => {
-      if(executeResult.code == "200") {
-        console.log("In promise")
-        console.log(executeResult)
+      if(executeResult.code === "200") {
+        console.log("In promise");
+        console.log(executeResult);
         var listItem = {};
 
-        console.log(identity)
-        listItem.identityColor = getColorForIdentity(identity.authentication.publicKey)
-        listItem.initials = executeResult.data.initials
+        console.log(identity);
+        listItem.identityColor = getColorForIdentity(identity.authentication.publicKey);
+        listItem.initials = executeResult.data.initials;
 
         if(listItem.initials === null || listItem.initials === "") {
           listItem.initials = "JD";
         }
-        console.log("Item")
-        console.log(listItem)
-        localStorage.setItem("profiles/" + identity.authentication.publicKey, JSON.stringify(listItem))
+        console.log("Item");
+        console.log(listItem);
+        localStorage.setItem("profiles/" + identity.authentication.publicKey, JSON.stringify(listItem));
         executeResultUpper(listItem)
       } else {
         executeResultUpper({})
@@ -1217,19 +1215,19 @@ function getProfileData(identity) {
 function getIdentityFromLocalStorage(key, pinCode, extendTtl = true) {
   const encryptedIdentity = localStorage.getItem(key);
   if (encryptedIdentity == null) {
-    console.log("No such identity for public key")
+    console.log("No such identity for public key");
     return Promise.resolve(null)
   }
   return decryptMessage(encryptedIdentity, pinCode).then((serializedIdentity) => {
     var parsedIdentity = JSON.parse(serializedIdentity);
-    parsedIdentity["pinCode"] = ""
+    parsedIdentity["pinCode"] = "";
     //console.log(parsedIdentity)
     if(extendTtl === true) {
-      var success = extendPinCodeTtl(key, pinCode)
-      if (success == true) {
+      var success = extendPinCodeTtl(key, pinCode);
+      if (success === true) {
         return parsedIdentity
       } else {
-        console.log("Can not extend pincode ttl")
+        console.log("Can not extend pincode ttl");
         return null
       }
     } else {
@@ -1240,50 +1238,42 @@ function getIdentityFromLocalStorage(key, pinCode, extendTtl = true) {
 }
 
 function listIdentitiesFromLocalStorage() {
-  var serializedIdentitiesList = localStorage.getItem("identities")
-  var identities = JSON.parse(serializedIdentitiesList)
-  var identitiesResult = {}
+  var serializedIdentitiesList = localStorage.getItem("identities");
+  var identities = JSON.parse(serializedIdentitiesList);
+  var identitiesResult = {};
 
   for(var key in identities) {
-    var profile = JSON.parse(JSON.stringify(localStorage.getItem("profiles/" + key)))
-    console.log("Getting profile")
-    console.log(profile)
-    if(profile != null && profile != "") {
-      console.log("Setting profile for key: " + key)
+    var profile = JSON.parse(JSON.stringify(localStorage.getItem("profiles/" + key)));
+    console.log("Getting profile");
+    console.log(profile);
+    if(profile != null && profile !== "") {
+      console.log("Setting profile for key: " + key);
       //console.log(profile)
       identitiesResult[key] = JSON.parse(profile)
       //console.log(identitiesResult)
     } else {
-      console.log("Setting empty key for profile: " + key)
+      console.log("Setting empty key for profile: " + key);
       identitiesResult[key] = {}
       //console.log(identitiesResult)
     }
   }
 
-  console.log("In list identities from local storage")
-  console.log(identitiesResult)
+  console.log("In list identities from local storage");
+  console.log(identitiesResult);
   return identitiesResult
 }
 
-function getStack() {
-  try {
-    throw new Error();
-  } catch(e) {
-    return e.stack;
-  }
-}
-
 function extendPinCodeTtl(key, pinCode) {
   //console.log("Extending pincode ttl")
   //console.log(getStack())
   //console.log("Extending pincode ttl for key: " + key)
   //console.log(pinCode)
-  if(pinCode == null || pinCode == "") {
+  if(pinCode == null || pinCode === "") {
     var now = new Date();
     var nowMillis = now.getTime();
     var ttl = window.sessionStorage.getItem("pincodettls/" + key);
-    if (ttl == null || ttl == "" || nowMillis >= parseInt(ttl)) {
-      clearPinCodeTtl(key)
+    if (ttl == null || ttl === "" || nowMillis >= parseInt(ttl)) {
+      clearPinCodeTtl(key);
       return false
     } else {
       var ttl = now.getTime() + 24 * 60 * 60 * 1000;
@@ -1303,7 +1293,7 @@ window.extendPinCodeTtl = extendPinCodeTtl;
 
 function clearPinCodeTtl(key) {
   //console.log("Clearing ttl for key: " + key)
-  window.sessionStorage.removeItem("pincodettls/" + key)
+  window.sessionStorage.removeItem("pincodettls/" + key);
   window.sessionStorage.removeItem("pincodes/" + key)
 }
 
@@ -1311,11 +1301,11 @@ function getPincode(key) {
   var now = new Date();
   var nowMillis = now.getTime();
   var ttl = window.sessionStorage.getItem("pincodettls/" + key);
-  if (ttl == null || ttl == "") {
+  if (ttl == null || ttl === "") {
     return null
   } else {
     if(nowMillis >= parseInt(ttl)) {
-      clearPinCodeTtl(key)
+      clearPinCodeTtl(key);
       return null
     } else {
       return window.sessionStorage.getItem("pincodes/" + key);
@@ -1333,140 +1323,121 @@ function createEvent(actionId, type, payloads) {
 }
 
 function destroyIdentityFromLocalStorage(key) {
-  localStorage.removeItem(key)
-  localStorage.removeItem("profiles/" + key)
-  localStorage.removeItem("colors/" + key)
+  localStorage.removeItem(key);
+  localStorage.removeItem("profiles/" + key);
+  localStorage.removeItem("colors/" + key);
 
-  var serializedIdentitiesList = localStorage.getItem("identities")
+  var serializedIdentitiesList = localStorage.getItem("identities");
 
-  var identities = JSON.parse(serializedIdentitiesList)
+  var identities = JSON.parse(serializedIdentitiesList);
 
-  identities[key] = null
+  identities[key] = null;
 
-  delete identities[key]
+  delete identities[key];
 
   localStorage.setItem("identities", JSON.stringify(identities))
 }
 
-window.loadedIdentities = {}
+window.loadedIdentities = {};
 window.wopiAPI = new WopiAPI();
 window.viamApi = new ViamAPI();
 window.viamAnonymousApi = new ViamAPI();
-window.currentlyAuthenticatedIdentity = null
-window.currentlyLoadedIdentity = null
-window.lastTimeGetProfile = 0
+window.currentlyAuthenticatedIdentity = null;
+window.currentlyLoadedIdentity = null;
+window.lastTimeGetProfile = 0;
+
+const handleIdentityLogin = async (identity, uuid, token) => {
+  try {
+    const { loadedIdentities, viamApi } = window;
+    const { publicKey } = identity.authentication;
+
+    const deviceHash = await createDeviceHash(publicKey);
+
+    viamApi.setSessionData(uuid, token, deviceHash, navigator.userAgent);
+    localStorage.setItem("uuid", uuid);
+    localStorage.setItem("token", token);
+    localStorage.setItem("authenticatedIdentity", publicKey);
+    window.currentlyAuthenticatedIdentity = loadedIdentities[publicKey];
+    window.lastTimeGetProfile = 0;
+    setKeyForUUID(uuid, publicKey);
+  } catch (error) {
+    console.warn(error);
+  }
+
+};
 
 function executeRestfulFunction(type, that, fn, ...args) {
-  if(type == "private") {
-    return new Penpal.Promise(executeResult => {
-      fn.apply(that, args).then((response) => {
-        if (response.data.code == "400" && response.data.status == "Bad session") {
-          console.log("Trying to login again")
-          if(currentlyAuthenticatedIdentity != "" && currentlyAuthenticatedIdentity != null) {
-            viamApi.identityLogin("previousaddeddevice").then((response1) => {
-              if (response1.data.code == "200") {
-                //console.log(response.data.data)
-                var uuid = response1.data.data["Uuid"]
-                var token = response1.data.data["Session"]
-                //console.log(uuid + " " + token)
-                viamApi.setSessionData(uuid, token)
-                localStorage.setItem("uuid", uuid)
-                localStorage.setItem("token", token)
-                localStorage.setItem("authenticatedIdentity", currentlyAuthenticatedIdentity.authentication.publicKey)
-                currentlyAuthenticatedIdentity = loadedIdentities[currentlyAuthenticatedIdentity.authentication.publicKey]
-                setKeyForUUID(uuid, currentlyAuthenticatedIdentity.authentication.publicKey)
-                lastTimeGetProfile = 0;
-                fn.apply(null, args).then((response2) => {
-                  executeResult(response2.data)
-                });
-              } else {
-                executeResult(response1.data)
-              }
-            });
-          } else {
-            if(currentlyLoadedIdentity != "" && currentlyLoadedIdentity != null) {
-              viamApi.identityLogin("previousaddeddevice").then((response1) => {
-                if (response1.data.code == "200") {
-                  //console.log(response.data.data)
-                  var uuid = response1.data.data["Uuid"]
-                  var token = response1.data.data["Session"]
-                  //console.log(uuid + " " + token)
-                  viamApi.setSessionData(uuid, token)
-                  localStorage.setItem("uuid", uuid)
-                  localStorage.setItem("token", token)
-                  localStorage.setItem("authenticatedIdentity", currentlyLoadedIdentity.authentication.publicKey)
-                  currentlyAuthenticatedIdentity = loadedIdentities[currentlyLoadedIdentity.authentication.publicKey]
-                  setKeyForUUID(uuid, currentlyLoadedIdentity.authentication.publicKey)
-                  lastTimeGetProfile = 0;
-                  fn.apply(null, args).then((response2) => {
-                    executeResult(response2.data)
-                  });
-                } else {
-                  executeResult(response1.data)
-                }
-              });
+  const { currentlyAuthenticatedIdentity, viamApi, currentlyLoadedIdentity } = window;
+
+  return new Penpal.Promise(executeResult => {
+    fn.apply(that, args).then((response) => {
+      const identity = currentlyAuthenticatedIdentity || currentlyLoadedIdentity;
+
+      if (type === "private" && identity && response.data.code === "400" && response.data.status === "Bad session") {
+        viamApi.identityLogin("previousaddeddevice")
+          .then(async (response) => {
+            if (response.data.code === "200") {
+              const uuid = response.data.data["Uuid"];
+              const token = response.data.data["Session"];
+              await handleIdentityLogin(identity, uuid, token);
+              // TODO: Previously there was fn.apply(null, args) where null is probably wrong context for fn.apply()
+              fn.apply(that, args).then(({data}) => executeResult(data));
             } else {
-              executeResult(response.data)
+              executeResult(response.data);
             }
-          }
-        } else {
-          executeResult(response.data)
-        }
-      });
-    });
-  } else {
-    return new Penpal.Promise(executeResult => {
-      fn.apply(that, args).then((response) => {
-        executeResult(response.data)
-      });
+          })
+          .catch(console.warn);
+      } else {
+        executeResult(response.data);
+      }
     });
-  }
+  });
 }
 
 window.executeRestfulFunction = executeRestfulFunction;
 
 function loadIdentityInternal(identityKey, pinCode) {
   return new Penpal.Promise(result => {
-    console.log("Loading identity with pincode: " + pinCode)
-    getIdentityFromLocalStorage(identityKey, pinCode).then((loadedIdentity) => {
+    console.log("Loading identity with pincode: " + pinCode);
+    getIdentityFromLocalStorage(identityKey, pinCode).then(async (loadedIdentity) => {
       if (loadedIdentity == null) {
         result({
           "data": "",
           "code": "400",
           "status": "Can not load identity"
-        })
+        });
       }
-      var copiedIdentity = JSON.parse(JSON.stringify(loadedIdentity))
-      loadedIdentities[identityKey] = loadedIdentity
+      const copiedIdentity = JSON.parse(JSON.stringify(loadedIdentity));
+      window.loadedIdentities[identityKey] = loadedIdentity;
 
       if (identityKey === localStorage.getItem("authenticatedIdentity")) {
-        currentlyAuthenticatedIdentity = copiedIdentity
-        viamApi.setIdentity(identityKey)
-        var uuid = localStorage.getItem("uuid")
-        var token = localStorage.getItem("token")
-        //console.log("Loading " + uuid + " " + token)
-        viamApi.setSessionData(uuid, token)
+        window.currentlyAuthenticatedIdentity = copiedIdentity;
+        window.viamApi.setIdentity(identityKey);
+        const uuid = localStorage.getItem("uuid");
+        const token = localStorage.getItem("token");
+        const deviceHash = await createDeviceHash(identityKey);
+        window.viamApi.setSessionData(uuid, token, deviceHash, navigator.userAgent);
       }
 
       //console.log("Set loaded identity in load identity")
-      currentlyLoadedIdentity = copiedIdentity
-      viamAnonymousApi.setIdentity(currentlyLoadedIdentity.authentication.publicKey)
+      window.currentlyLoadedIdentity = copiedIdentity;
+      window.viamAnonymousApi.setIdentity(window.currentlyLoadedIdentity.authentication.publicKey);
 
-      copiedIdentity.pinCode = ""
-      copiedIdentity.authentication.privateKey = ""
+      copiedIdentity.pinCode = "";
+      copiedIdentity.authentication.privateKey = "";
 
       result({
         "data": copiedIdentity,
         "code": "200",
         "status": "Identity loaded"
-      })
+      });
     }).catch((e) => {
       result({
         "data": "",
         "code": "400",
         "status": "Can not load entity:" + e
-      })
-    })
+      });
+    });
   });
 }
 
@@ -1477,7 +1448,7 @@ function changeIdentityPinCodeInternal(key, oldPinCode, newPinCode) {
 
       identity.pinCode = newPinCode;
 
-      console.log("Storing identity with pincode: " + identity.pinCode)
+      console.log("Storing identity with pincode: " + identity.pinCode);
       setIdentityInLocalStorage(identity).then(() => {
         result({
           "data": "",
@@ -1504,37 +1475,37 @@ function changeIdentityPinCodeInternal(key, oldPinCode, newPinCode) {
 function getCertificateForPassport(passportUUID, internal) {
 
   return new Penpal.Promise(certificateResult => {
-    if (currentlyAuthenticatedIdentity === null) {
+    if (window.currentlyAuthenticatedIdentity === null) {
       return {"data" : "",
         "code" : "400",
         "status" : "Identity not authenticated"
       }
     }
 
-    var passportIdentity = new Identity()
-    passportIdentity.set(currentlyAuthenticatedIdentity)
+    var passportIdentity = new Identity();
+    passportIdentity.set(window.currentlyAuthenticatedIdentity);
     //console.log("Getting: " + passportUUID)
     //console.log(identity)
-    var passport = passportIdentity.getPassport(passportUUID)
+    var passport = passportIdentity.getPassport(passportUUID);
     if(passport === undefined || passport === null) {
       createPassportCertificate(passportUUID).then(function(keys){
-        var cryptoData = new CryptoData()
+        var cryptoData = new CryptoData();
         //console.log(keys)
-        cryptoData.setPublicKey(keys["publicKeyPEM"])
-        cryptoData.setPrivateKey(keys["privateKeyPEM"])
-        var certificate = keys["certificatePEM"]
+        cryptoData.setPublicKey(keys["publicKeyPEM"]);
+        cryptoData.setPrivateKey(keys["privateKeyPEM"]);
+        var certificate = keys["certificatePEM"];
         //download("passportCertificateBeforeSigning.crt", "text/plain", certificate)
         //console.log(certificate)
         //cryptoData.setx509Certificate(keys["certificate"])
         executeRestfulFunction("private", viamApi, viamApi.signSignCertificate, btoa(certificate), passportUUID).then(executeResult => {
-          if(executeResult.code == "200") {
-            var signedCertificate = atob(executeResult.data["SignedCertificate"])
+          if(executeResult.code === "200") {
+            var signedCertificate = atob(executeResult.data["SignedCertificate"]);
             //download("passportCertificateAfterSigning.crt", "text/plain", signedCertificate)
-            var keyUUID = executeResult.data["CertificateUUID"]
-            var encodedChain = executeResult.data["Chain"]
+            var keyUUID = executeResult.data["CertificateUUID"];
+            var encodedChain = executeResult.data["Chain"];
             //download("rootCertificate.crt", "text/plain", atob(encodedChain[0]))
 
-            var chain = []
+            var chain = [];
 
             for(var i = 0; i < encodedChain.length; i++) {
               chain.push(atob(encodedChain[i]))
@@ -1545,23 +1516,22 @@ function getCertificateForPassport(passportUUID, internal) {
             //console.log(signedCertificate)
             //console.log(certificate)
             //console.log(keyUUID)
-            cryptoData.setx509Certificate(signedCertificate)
-            cryptoData.setKeyUUID(keyUUID)
-            cryptoData.setChain(chain)
+            cryptoData.setx509Certificate(signedCertificate);
+            cryptoData.setKeyUUID(keyUUID);
+            cryptoData.setChain(chain);
 
-            passportIdentity.setPassport(passportUUID, cryptoData)
+            passportIdentity.setPassport(passportUUID, cryptoData);
 
             getProfileData(passportIdentity).then(executeResult1 => {
-              console.log("Profile updated in set identity")
+              console.log("Profile updated in set identity");
               setIdentityInLocalStorage(passportIdentity).then(() => {
-                currentlyAuthenticatedIdentity = passportIdentity
-                lastTimeGetProfile = 0;
-                //console.log("Set loaded identity in passport");
-                currentlyLoadedIdentity = passportIdentity
-                var copyOfCryptoData = JSON.parse(JSON.stringify(cryptoData))
+                window.currentlyAuthenticatedIdentity = passportIdentity;
+                window.lastTimeGetProfile = 0;
+                window.currentlyLoadedIdentity = passportIdentity;
+                const copyOfCryptoData = JSON.parse(JSON.stringify(cryptoData));
 
                 if (internal === false) {
-                  copyOfCryptoData["privateKey"] = ""
+                  copyOfCryptoData["privateKey"] = "";
                 }
 
                 certificateResult({
@@ -1578,13 +1548,13 @@ function getCertificateForPassport(passportUUID, internal) {
               });
             });
           } else {
-            certificateResult(executeResult)
+            certificateResult(executeResult);
           }
         });
       });
     } else {
       //console.log(passport)
-      var copyOfCryptoData = JSON.parse(JSON.stringify(passport))
+      var copyOfCryptoData = JSON.parse(JSON.stringify(passport));
 
       if(internal === false) {
         copyOfCryptoData["privateKey"] = ""
@@ -1607,21 +1577,20 @@ const connection = Penpal.connectToParent({
     createIdentity(pinCode) {
       return new Penpal.Promise(result => {
         createPassportCertificate(makeid()).then(function(keys){
-          var newIdentity = new Identity()
-          var cryptoData = new CryptoData()
-          cryptoData.setPublicKey(keys["publicKeyPEM"])
-          cryptoData.setPrivateKey(keys["privateKeyPEM"])
-          cryptoData.setx509Certificate(keys["certificatePEM"])
-          newIdentity.setAuthentication(cryptoData)
-          newIdentity.setPinCode(pinCode)
+          var newIdentity = new Identity();
+          var cryptoData = new CryptoData();
+          cryptoData.setPublicKey(keys["publicKeyPEM"]);
+          cryptoData.setPrivateKey(keys["privateKeyPEM"]);
+          cryptoData.setx509Certificate(keys["certificatePEM"]);
+          newIdentity.setAuthentication(cryptoData);
+          newIdentity.setPinCode(pinCode);
 
           //console.log("Set loaded identity in createIdentity")
-          currentlyLoadedIdentity = newIdentity
-          loadedIdentities[newIdentity.authentication.publicKey] = newIdentity
-          extendPinCodeTtl(newIdentity.authentication.publicKey, pinCode)
-
+          window.currentlyLoadedIdentity = newIdentity;
+          window.loadedIdentities[newIdentity.authentication.publicKey] = newIdentity;
+          extendPinCodeTtl(newIdentity.authentication.publicKey, pinCode);
 
-          viamAnonymousApi.setIdentity(newIdentity.authentication.publicKey)
+          window.viamAnonymousApi.setIdentity(newIdentity.authentication.publicKey);
 
           result({"data" : newIdentity,
             "code" : "200",
@@ -1632,9 +1601,9 @@ const connection = Penpal.connectToParent({
     },
     listIdentities() {
       return new Penpal.Promise(result => {
-        var identities = listIdentitiesFromLocalStorage()
-        console.log("Before return of identities")
-        console.log(identities)
+        var identities = listIdentitiesFromLocalStorage();
+        console.log("Before return of identities");
+        console.log(identities);
         result({"data" : identities,
           "code" : "200",
           "status" : "Identities listed"
@@ -1649,8 +1618,8 @@ const connection = Penpal.connectToParent({
     },
     getIdentityProfile(identityKey) {
       return new Penpal.Promise(result => {
-        serializedProfile = localStorage.getItem("profiles/" + identityKey)
-        if(serializedProfile == null || serializedProfile == "") {
+        const serializedProfile = localStorage.getItem("profiles/" + identityKey);
+        if (serializedProfile === null || serializedProfile === "") {
           result({"data" : "",
             "code" : "400",
             "status" : "Profile is empty"
@@ -1665,7 +1634,7 @@ const connection = Penpal.connectToParent({
     },
     clearIdentities() {
       return new Penpal.Promise(result => {
-        var identitiesTemp = listIdentitiesFromLocalStorage()
+        var identitiesTemp = listIdentitiesFromLocalStorage();
         //console.log(identitiesTemp.length)
         for(var i in identitiesTemp) {
           destroyIdentityFromLocalStorage(i)
@@ -1678,7 +1647,7 @@ const connection = Penpal.connectToParent({
     },
     confirmIdentificator(identity, confirmationCodeArg) {
       return new Penpal.Promise(result => {
-        viamApi.setIdentity(identity.authentication.publicKey)
+        viamApi.setIdentity(identity.authentication.publicKey);
 
         executeRestfulFunction("public", viamApi, viamApi.identityConfirmIdentificator,confirmationCodeArg).then(executeResult => {
           result(executeResult);
@@ -1687,7 +1656,7 @@ const connection = Penpal.connectToParent({
     },
     identityGetIdentificatorByRegisterToken(identity, tokenArg) {
       return new Penpal.Promise(result => {
-        viamApi.setIdentity(identity.authentication.publicKey)
+        viamApi.setIdentity(identity.authentication.publicKey);
 
         executeRestfulFunction("public", viamApi, viamApi.identityGetIdentificatorByRegisterToken,tokenArg).then(executeResult => {
           result(executeResult);
@@ -1696,7 +1665,7 @@ const connection = Penpal.connectToParent({
     },
     submitIdentificator(identity, identificatorArg, registerToken) {
       return new Penpal.Promise(result => {
-        viamApi.setIdentity(identity.authentication.publicKey)
+        viamApi.setIdentity(identity.authentication.publicKey);
 
         executeRestfulFunction("public", viamApi, viamApi.identitySubmitIdentificator,identificatorArg, registerToken).then(executeResult => {
           result(executeResult);
@@ -1705,7 +1674,7 @@ const connection = Penpal.connectToParent({
     },
     submitRegisterClaims(identity, givennameArg,familynameArg,emailArg,phonenumberArg) {
       return new Penpal.Promise(result => {
-        viamApi.setIdentity(identity.authentication.publicKey)
+        viamApi.setIdentity(identity.authentication.publicKey);
 
         executeRestfulFunction("public", viamApi, viamApi.identitySubmitRegisterClaims,givennameArg,familynameArg,emailArg,phonenumberArg).then(executeResult => {
           result(executeResult);
@@ -1714,12 +1683,12 @@ const connection = Penpal.connectToParent({
     },
     agreeOnRegistration(registerIdentity) {
       return new Penpal.Promise(result => {
-        viamApi.setIdentity(registerIdentity.authentication.publicKey)
+        viamApi.setIdentity(registerIdentity.authentication.publicKey);
 
         executeRestfulFunction("public", viamApi, viamApi.identityAgreeOnRegistration).then(executeResult => {
-          console.log("Profile updated in set identity")
+          console.log("Profile updated in set identity");
 
-          let sequence = Promise.resolve()
+          let sequence = Promise.resolve();
           if (executeResult.code === "200") {
             sequence = sequence.then(() => {
                 setIdentityInLocalStorage(registerIdentity)
@@ -1740,7 +1709,7 @@ const connection = Penpal.connectToParent({
     },
     resendConfirmationCode(identity, identificatorArg) {
       return new Penpal.Promise(result => {
-        viamApi.setIdentity(identity.authentication.publicKey)
+        viamApi.setIdentity(identity.authentication.publicKey);
 
         executeRestfulFunction("public", viamApi, viamApi.identityResendConfirmationCode,identificatorArg).then(executeResult => {
           result(executeResult);
@@ -1749,7 +1718,7 @@ const connection = Penpal.connectToParent({
     },
     login(loginIdentity, mode, code, actionID) {
       return new Penpal.Promise(result => {
-        if (loadedIdentities[loginIdentity.authentication.publicKey] === null) {
+        if (window.loadedIdentities[loginIdentity.authentication.publicKey] === null) {
           result({"data" : "",
             "code" : "400",
             "status" : "Identity not loaded"
@@ -1758,54 +1727,35 @@ const connection = Penpal.connectToParent({
 
         //console.log("After loaded check")
 
-        viamApi.setIdentity(loginIdentity.authentication.publicKey)
+        viamApi.setIdentity(loginIdentity.authentication.publicKey);
 
-        executeRestfulFunction("public", viamApi, viamApi.identityLogin, mode, code, actionID).then(executeResult => {
+        executeRestfulFunction("public", viamApi, viamApi.identityLogin, mode, code, actionID).then(async executeResult => {
           // console.log(executeResult)
           //console.log(mode)
-          switch(mode) {
+          switch (mode) {
             case "sms" : {
               if (executeResult.code === "200") {
-                //console.log("In if")
-                var uuid = executeResult.data["Uuid"]
-                var token = executeResult.data["Session"]
-                viamApi.setSessionData(uuid, token)
-                localStorage.setItem("uuid", uuid)
-                localStorage.setItem("token", token)
-                localStorage.setItem("authenticatedIdentity",
-                  loginIdentity.authentication.publicKey)
-                setKeyForUUID(uuid, loginIdentity.authentication.publicKey)
-                currentlyAuthenticatedIdentity = loadedIdentities[loginIdentity.authentication.publicKey]
-                lastTimeGetProfile = 0;
-                delete executeResult.data["Uuid"]
-                delete executeResult.data["Session"]
+                const uuid = executeResult.data["Uuid"];
+                const token = executeResult.data["Session"];
+                await handleIdentityLogin(loginIdentity, uuid, token);
+                delete executeResult.data["Uuid"];
+                delete executeResult.data["Session"];
                 getProfileData(loginIdentity).then(executeResult1 => {
                   result(executeResult);
                 });
               } else {
-                //console.log("In else")
                 result(executeResult);
               }
 
               break;
             }
-
             case "previousaddeddevice" : {
               if (executeResult.code === "200") {
-                //console.log(response.data.data)
-                var uuid = executeResult.data["Uuid"]
-                var token = executeResult.data["Session"]
-                //console.log(uuid + " " + token)
-                viamApi.setSessionData(uuid, token)
-                localStorage.setItem("uuid", uuid)
-                localStorage.setItem("token", token)
-                localStorage.setItem("authenticatedIdentity",
-                  loginIdentity.authentication.publicKey)
-                setKeyForUUID(uuid, loginIdentity.authentication.publicKey)
-                currentlyAuthenticatedIdentity = loadedIdentities[loginIdentity.authentication.publicKey]
-                lastTimeGetProfile = 0;
-                delete executeResult.data["Uuid"]
-                delete executeResult.data["Session"]
+                const uuid = executeResult.data["Uuid"];
+                const token = executeResult.data["Session"];
+                await handleIdentityLogin(loginIdentity, uuid, token);
+                delete executeResult.data["Uuid"];
+                delete executeResult.data["Session"];
                 getProfileData(loginIdentity).then(executeResult1 => {
                   result(executeResult);
                 });
@@ -1819,11 +1769,11 @@ const connection = Penpal.connectToParent({
             case "newdevice" : {
               if (executeResult.code === "200") {
                 //console.log(executeResult)
-                var actionID = executeResult.data["ActionID"]
-                var QrCode = executeResult.data["QrCode"]
+                var actionID = executeResult.data["ActionID"];
+                var QrCode = executeResult.data["QrCode"];
                 //console.log(uuid + " " + token)
                 QRCode.toDataURL(actionID + "," + QrCode, function (err, url) {
-                  executeResult.data["image"] = url
+                  executeResult.data["image"] = url;
                   //console.log(executeResult)
                   result(executeResult);
                 })
@@ -1844,25 +1794,25 @@ const connection = Penpal.connectToParent({
     },
     identityAddNewDevice() {
       return new Penpal.Promise(result => {
-        authenticationPublicKey = localStorage.getItem("authenticatedIdentity")
+        window.authenticationPublicKey = localStorage.getItem("authenticatedIdentity");
 
-        if (authenticationPublicKey === null) {
+        if (window.authenticationPublicKey === null) {
           result({"data" : "",
             "code" : "400",
             "status" : "Identity not authenticated"
           })
         }
 
-        if (loadedIdentities[authenticationPublicKey] === null) {
+        if (window.loadedIdentities[authenticationPublicKey] === null) {
           result({"data" : "",
             "code" : "400",
             "status" : "Identity not authenticated"
           })
         }
 
-        var success = extendPinCodeTtl(authenticationPublicKey)
+        var success = extendPinCodeTtl(authenticationPublicKey);
 
-        if(success == false) {
+        if(success === false) {
           result({"data" : "",
             "code" : "400",
             "status" : "Identity not authenticated"
@@ -1870,13 +1820,13 @@ const connection = Penpal.connectToParent({
         }
 
         executeRestfulFunction("private", viamApi, viamApi.identityAddNewDevice).then(executeResult => {
-          if (executeResult.code == "200") {
+          if (executeResult.code === "200") {
             //console.log(response.data.data)
-            var actionID = executeResult.data["ActionID"]
-            var QrCode = executeResult.data["QrCode"]
+            var actionID = executeResult.data["ActionID"];
+            var QrCode = executeResult.data["QrCode"];
             //console.log(uuid + " " + token)
             QRCode.toDataURL(actionID + "," + QrCode, function (err, url) {
-              executeResult.data["image"] = url
+              executeResult.data["image"] = url;
               result(executeResult);
             })
           } else {
@@ -1887,23 +1837,23 @@ const connection = Penpal.connectToParent({
     },
     identityDestroyKeysForDevice(authenticationPublicKeyArg) {
       return new Penpal.Promise(result => {
-        authenticationPublicKey = localStorage.getItem("authenticatedIdentity")
-        if (authenticationPublicKey === null) {
+        window.authenticationPublicKey = localStorage.getItem("authenticatedIdentity");
+        if (window.authenticationPublicKey === null) {
           result({"data" : "",
             "code" : "400",
             "status" : "Identity not authenticated"
           })
         }
-        if (loadedIdentities[authenticationPublicKey] === null) {
+        if (window.loadedIdentities[authenticationPublicKey] === null) {
           result({"data" : "",
             "code" : "400",
             "status" : "Identity not authenticated"
           })
         }
 
-        var success = extendPinCodeTtl(authenticationPublicKey)
+        var success = extendPinCodeTtl(authenticationPublicKey);
 
-        if(success == false) {
+        if(success === false) {
           result({"data" : "",
             "code" : "400",
             "status" : "Identity not authenticated"
@@ -1916,14 +1866,14 @@ const connection = Penpal.connectToParent({
       });
     },
     logout() {
-      authenticationPublicKey = localStorage.getItem("authenticatedIdentity")
-      if (authenticationPublicKey === null) {
+      window.authenticationPublicKey = localStorage.getItem("authenticatedIdentity");
+      if (window.authenticationPublicKey === null) {
         return {"data" : "",
           "code" : "400",
           "status" : "Identity not loaded"
         }
       }
-      if (loadedIdentities[authenticationPublicKey] === null) {
+      if (window.loadedIdentities[authenticationPublicKey] === null) {
         return {"data" : "",
           "code" : "400",
           "status" : "Identity not loaded"
@@ -1932,19 +1882,19 @@ const connection = Penpal.connectToParent({
 
       return new Penpal.Promise(result => {
         executeRestfulFunction("private", viamApi, viamApi.identityLogout).then(executeResult => {
-          viamApi.setIdentity("")
-          viamApi.setSessionData("", "")
-          clearPinCodeTtl(authenticationPublicKey)
-
-          authenticationPublicKey = localStorage.getItem("authenticatedIdentity")
-          localStorage.removeItem("uuid")
-          localStorage.removeItem("token")
-          localStorage.removeItem("authenticatedIdentity")
-          delete loadedIdentities[authenticationPublicKey]
+          viamApi.setIdentity("");
+          viamApi.setSessionData("", "", "", "");
+          clearPinCodeTtl(authenticationPublicKey);
+
+          window.authenticationPublicKey = localStorage.getItem("authenticatedIdentity");
+          localStorage.removeItem("uuid");
+          localStorage.removeItem("token");
+          localStorage.removeItem("authenticatedIdentity");
+          delete window.loadedIdentities[authenticationPublicKey];
           //console.log("Set loaded identity in logout")
-          currentlyLoadedIdentity = null
-          currentlyAuthenticatedIdentity = null
-          lastTimeGetProfile = 0;
+          window.currentlyLoadedIdentity = null;
+          window.currentlyAuthenticatedIdentity = null;
+          window.lastTimeGetProfile = 0;
 
           result(executeResult);
         });
@@ -1952,11 +1902,11 @@ const connection = Penpal.connectToParent({
     },
     identityRestoreAccess(restoreAccessIdentity, identificator) {
       return new Penpal.Promise(result => {
-        viamApi.setIdentity(restoreAccessIdentity.authentication.publicKey)
+        viamApi.setIdentity(restoreAccessIdentity.authentication.publicKey);
 
         executeRestfulFunction("public", viamApi, viamApi.identityRestoreAccess, identificator).then(executeResult => {
           if (executeResult.code === "200") {
-            setIdentityInLocalStorage(restoreAccessIdentity)
+            setIdentityInLocalStorage(restoreAccessIdentity);
             result(executeResult);
           } else {
             result(executeResult);
@@ -1966,23 +1916,23 @@ const connection = Penpal.connectToParent({
     },
     getCurrentlyLoggedInUUID() {
       return new Penpal.Promise(result => {
-        authenticationPublicKey = localStorage.getItem("authenticatedIdentity")
-        if (authenticationPublicKey === null) {
+        window.authenticationPublicKey = localStorage.getItem("authenticatedIdentity");
+        if (window.authenticationPublicKey === null) {
           return {"data" : "",
             "code" : "400",
             "status" : "Identity not loaded"
           }
         }
-        if (loadedIdentities[authenticationPublicKey] === null) {
+        if (window.loadedIdentities[authenticationPublicKey] === null) {
           return {"data" : "",
             "code" : "400",
             "status" : "Identity not loaded"
           }
         }
 
-        var success = extendPinCodeTtl(authenticationPublicKey)
+        var success = extendPinCodeTtl(authenticationPublicKey);
 
-        if(success == false) {
+        if(success === false) {
           result({"data" : "",
             "code" : "400",
             "status" : "Identity not authenticated"
@@ -2003,23 +1953,23 @@ const connection = Penpal.connectToParent({
     },
     getCertificateByPassport(passportUUID) {
       return new Penpal.Promise(result => {
-        authenticationPublicKey = localStorage.getItem("authenticatedIdentity")
-        if (authenticationPublicKey === null) {
+        window.authenticationPublicKey = localStorage.getItem("authenticatedIdentity");
+        if (window.authenticationPublicKey === null) {
           return {"data" : "",
             "code" : "400",
             "status" : "Identity not loaded"
           }
         }
-        if (loadedIdentities[authenticationPublicKey] === null) {
+        if (window.loadedIdentities[authenticationPublicKey] === null) {
           return {"data" : "",
             "code" : "400",
             "status" : "Identity not loaded"
           }
         }
 
-        var success = extendPinCodeTtl(authenticationPublicKey)
+        var success = extendPinCodeTtl(authenticationPublicKey);
 
-        if(success == false) {
+        if(success === false) {
           result({"data" : "",
             "code" : "400",
             "status" : "Identity not authenticated"
@@ -2034,23 +1984,23 @@ const connection = Penpal.connectToParent({
     },
     getOneTimeCertificateByPassport(passportUUID, emailArg) {
       return new Penpal.Promise(result => {
-        authenticationPublicKey = localStorage.getItem("authenticatedIdentity")
-        if (authenticationPublicKey === null) {
+        window.authenticationPublicKey = localStorage.getItem("authenticatedIdentity");
+        if (window.authenticationPublicKey === null) {
           return {"data" : "",
             "code" : "400",
             "status" : "Identity not loaded"
           }
         }
-        if (loadedIdentities[authenticationPublicKey] === null) {
+        if (window.loadedIdentities[authenticationPublicKey] === null) {
           return {"data" : "",
             "code" : "400",
             "status" : "Identity not loaded"
           }
         }
 
-        var success = extendPinCodeTtl(authenticationPublicKey)
+        var success = extendPinCodeTtl(authenticationPublicKey);
 
-        if(success == false) {
+        if(success === false) {
           result({"data" : "",
             "code" : "400",
             "status" : "Identity not authenticated"
@@ -2059,22 +2009,22 @@ const connection = Penpal.connectToParent({
 
         getCertificateForPassport(passportUUID, true).then(certificateResult => {
           //console.log(certificateResult)
-          if(certificateResult.code == "200") {
-            var passportCertificate = certificateResult.data["x509Certificate"]
-            var passportPrivateKey = certificateResult.data["privateKey"]
-            var passportChain = certificateResult.data["chain"]
+          if(certificateResult.code === "200") {
+            var passportCertificate = certificateResult.data["x509Certificate"];
+            var passportPrivateKey = certificateResult.data["privateKey"];
+            var passportChain = certificateResult.data["chain"];
 
             createOneTimePassportCertificate(makeid() + "-" + passportUUID, emailArg, passportPrivateKey, passportCertificate).then(function(keys){
-              var publicKeyOneTime = keys["publicKeyPEM"]
-              var privateKeyOneTime = keys["privateKeyPEM"]
-              var certificateOneTime = keys["certificatePEM"]
-              passportChain.push(passportCertificate)
+              var publicKeyOneTime = keys["publicKeyPEM"];
+              var privateKeyOneTime = keys["privateKeyPEM"];
+              var certificateOneTime = keys["certificatePEM"];
+              passportChain.push(passportCertificate);
 
               var oneTimeCryptoData = new CryptoData();
-              oneTimeCryptoData.setx509Certificate(certificateOneTime)
-              oneTimeCryptoData.setPrivateKey(privateKeyOneTime)
-              oneTimeCryptoData.setPublicKey(publicKeyOneTime)
-              oneTimeCryptoData.setChain(passportChain)
+              oneTimeCryptoData.setx509Certificate(certificateOneTime);
+              oneTimeCryptoData.setPrivateKey(privateKeyOneTime);
+              oneTimeCryptoData.setPublicKey(publicKeyOneTime);
+              oneTimeCryptoData.setChain(passportChain);
 
               result({"data" : oneTimeCryptoData,
                 "code" : "200",
@@ -2095,23 +2045,23 @@ const connection = Penpal.connectToParent({
     },
     signEmail(passportUUID, emailArg, emailMessage) {
       return new Penpal.Promise(result => {
-        authenticationPublicKey = localStorage.getItem("authenticatedIdentity")
-        if (authenticationPublicKey === null) {
+        window.authenticationPublicKey = localStorage.getItem("authenticatedIdentity");
+        if (window.authenticationPublicKey === null) {
           return {"data" : "",
             "code" : "400",
             "status" : "Identity not authenticated"
           }
         }
-        if (loadedIdentities[authenticationPublicKey] === null) {
+        if (window.loadedIdentities[authenticationPublicKey] === null) {
           return {"data" : "",
             "code" : "400",
             "status" : "Identity not authenticated"
           }
         }
 
-        var success = extendPinCodeTtl(authenticationPublicKey)
+        var success = extendPinCodeTtl(authenticationPublicKey);
 
-        if(success == false) {
+        if(success === false) {
           result({"data" : "",
             "code" : "400",
             "status" : "Identity not authenticated"
@@ -2119,20 +2069,20 @@ const connection = Penpal.connectToParent({
         }
 
         getCertificateForPassport(passportUUID, true).then(certificateResult => {
-          console.log("Certificate for passport")
-          console.log(certificateResult)
-          if(certificateResult.code == "200") {
-            var passportCertificate = certificateResult.data["x509Certificate"]
-            var passportPrivateKey = certificateResult.data["privateKey"]
-            var passportChain = certificateResult.data["chain"]
+          console.log("Certificate for passport");
+          console.log(certificateResult);
+          if(certificateResult.code === "200") {
+            var passportCertificate = certificateResult.data["x509Certificate"];
+            var passportPrivateKey = certificateResult.data["privateKey"];
+            var passportChain = certificateResult.data["chain"];
 
             createOneTimePassportCertificate(makeid() + "-" + passportUUID, emailArg, passportPrivateKey, passportCertificate).then(function(keys){
-              var publicKeyOneTime = keys["publicKeyPEM"]
-              var privateKeyOneTime = keys["privateKeyPEM"]
-              var certificateOneTime = keys["certificatePEM"]
+              var publicKeyOneTime = keys["publicKeyPEM"];
+              var privateKeyOneTime = keys["privateKeyPEM"];
+              var certificateOneTime = keys["certificatePEM"];
               //download("certificateOneTime.crt", "text/plain", certificateOneTime)
 
-              passportChain.push(passportCertificate)
+              passportChain.push(passportCertificate);
 
               //console.log("Before sign email")
               //console.log(certificateOneTime)
@@ -2141,13 +2091,13 @@ const connection = Penpal.connectToParent({
 
               executeRestfulFunction("private", viamApi, viamApi.passportGetEmailWithHeaderByPassport,
                 passportUUID, emailMessage).then(executeResult2 => {
-                var emailWithHeader = executeResult2.data
+                var emailWithHeader = executeResult2.data;
                 //console.log(emailWithHeader)
                 //download("withheader.eml", "message/rfc822", emailWithHeader)
                 var signedEmailPromise = signEmail(emailWithHeader,
                   certificateOneTime,
                   passportChain,
-                  privateKeyOneTime)
+                  privateKeyOneTime);
 
                 signedEmailPromise.then(signedEmail => {
                   executeRestfulFunction("private", viamApi, viamApi.signResignEmail,
@@ -2178,23 +2128,23 @@ const connection = Penpal.connectToParent({
     },
     hasSession() {
       return new Penpal.Promise(result => {
-        authenticationPublicKey = localStorage.getItem("authenticatedIdentity")
-        if (authenticationPublicKey === null) {
+        window.authenticationPublicKey = localStorage.getItem("authenticatedIdentity");
+        if (window.authenticationPublicKey === null) {
           result({"data" : "",
             "code" : "400",
             "status" : "Identity not authenticated"
           });
         }
-        if (loadedIdentities[authenticationPublicKey] === null) {
+        if (window.loadedIdentities[authenticationPublicKey] === null) {
           result({"data" : "",
             "code" : "400",
             "status" : "Identity not authenticated"
           });
         }
 
-        var success = extendPinCodeTtl(authenticationPublicKey)
+        var success = extendPinCodeTtl(authenticationPublicKey);
 
-        if(success == false) {
+        if(success === false) {
           result({"data" : "",
             "code" : "400",
             "status" : "Identity not authenticated"
@@ -2208,40 +2158,40 @@ const connection = Penpal.connectToParent({
     },
     marketingSignUpIdentificator(identificator, reference) {
       return new Penpal.Promise(result => {
-        viamApi.setIdentity("marketingapppublickey")
+        viamApi.setIdentity("marketingapppublickey");
 
         executeRestfulFunction("public", viamApi, viamApi.marketingSignUpIdentificator, identificator, reference).then(executeResult => {
-          viamApi.setIdentity("")
-          viamApi.setSessionData("", "")
+          viamApi.setIdentity("");
+          viamApi.setSessionData("", "", "", "");
           result(executeResult);
         });
       });
     },
     marketingGetIdentificatorProfile(identificator, pincode) {
       return new Penpal.Promise(result => {
-        viamApi.setIdentity("marketingapppublickey")
+        viamApi.setIdentity("marketingapppublickey");
 
         executeRestfulFunction("public", viamApi, viamApi.marketingGetIdentificatorProfile, identificator, pincode).then(executeResult => {
-          viamApi.setIdentity("")
-          viamApi.setSessionData("", "")
+          viamApi.setIdentity("");
+          viamApi.setSessionData("", "", "", "");
           result(executeResult);
         });
       });
     },
     marketingExecuteEventForIdentificator(identificator, pincode, event) {
       return new Penpal.Promise(result => {
-        viamApi.setIdentity("marketingapppublickey")
+        viamApi.setIdentity("marketingapppublickey");
 
         executeRestfulFunction("public", viamApi, viamApi.marketingExecuteEventForIdentificator, identificator, pincode, event).then(executeResult => {
-          viamApi.setIdentity("")
-          viamApi.setSessionData("", "")
+          viamApi.setIdentity("");
+          viamApi.setSessionData("", "", "", "");
           result(executeResult);
         });
       });
     },
     getCurrentlyAuthenticatedIdentity() {
       return new Penpal.Promise(result => {
-        result({"data" : currentlyAuthenticatedIdentity,
+        result({"data" : window.currentlyAuthenticatedIdentity,
           "code" : "200",
           "status" : "Currently authenticated identity"
         })
@@ -2251,7 +2201,7 @@ const connection = Penpal.connectToParent({
       if (typeof str !== 'string') {
         str = str.toString()
       }
-      let res = Buffer.from(str,'utf-8')
+      let res = Buffer.from(str,'utf-8');
       return new Penpal.Promise(result => {
         result(res)
       })
@@ -2260,7 +2210,7 @@ const connection = Penpal.connectToParent({
       if (!Buffer.isBuffer(ba)) {
         ba = Buffer.from(ba)
       }
-      let res = ba.toString('utf-8')
+      let res = ba.toString('utf-8');
       return new Penpal.Promise(result => {
         result(res)
       })
@@ -2272,7 +2222,7 @@ const connection = Penpal.connectToParent({
         }
         str = Buffer.from(str, 'utf-8')
       }
-      let res = str.toString('base64')
+      let res = str.toString('base64');
       return new Penpal.Promise(result => {
         result(res)
       })
@@ -2284,7 +2234,7 @@ const connection = Penpal.connectToParent({
         }
         strBase64 = Buffer.from(strBase64, 'base64')
       }
-      let res = strBase64.toString('utf-8')
+      let res = strBase64.toString('utf-8');
       return new Penpal.Promise(result => {
         result(res)
       })
@@ -2293,7 +2243,7 @@ const connection = Penpal.connectToParent({
       if (typeof strBase64 !== 'string') {
         strBase64 = strBase64.toString()
       }
-      let res = Buffer.from(strBase64, 'base64')
+      let res = Buffer.from(strBase64, 'base64');
       return new Penpal.Promise(result => {
         result(res)
       })
@@ -2302,30 +2252,30 @@ const connection = Penpal.connectToParent({
       if (!Buffer.isBuffer(ba)) {
         ba = Buffer.from(ba)
       }
-      let res = ba.toString('base64')
+      let res = ba.toString('base64');
       return new Penpal.Promise(result => {
         result(res)
       })
     },
     ...penpalMethods
   }
-})
+});
 
 connection.promise.then(parent => {
 
   window.addEventListener('storage', event => {
     if (event.key === "authenticatedIdentity" && event.newValue === null) {
-      var publicKey = currentlyAuthenticatedIdentity.authentication.publicKey
-      currentlyLoadedIdentity = null
-      currentlyAuthenticatedIdentity = null
-      var event = createEvent("LogoutFromAnotherTab", "Logout", [publicKey])
+      var publicKey = window.currentlyAuthenticatedIdentity.authentication.publicKey;
+      window.currentlyLoadedIdentity = null;
+      window.currentlyAuthenticatedIdentity = null;
+      var event = createEvent("LogoutFromAnotherTab", "Logout", [publicKey]);
       parent.onEvent(event)
     }
   });
 
-  var identities = localStorage.getItem("identities")
+  var identities = localStorage.getItem("identities");
 
-  console.log("Library loaded at: " + new Date().toISOString())
+  console.log("Library loaded at: " + new Date().toISOString());
 
   if (identities === "" || identities === null) {
     //console.log("Setting up empty version")
@@ -2334,20 +2284,20 @@ connection.promise.then(parent => {
 
   if (localStorage.getItem("uuid") === null || localStorage.getItem("token") === null
     || localStorage.getItem("authenticatedIdentity") === null) {
-    localStorage.removeItem("uuid")
-    localStorage.removeItem("token")
+    localStorage.removeItem("uuid");
+    localStorage.removeItem("token");
     localStorage.removeItem("authenticatedIdentity")
   } else {
-    authenticationPublicKey = localStorage.getItem("authenticatedIdentity")
-    var pinCode = getPincode(authenticationPublicKey)
+    window.authenticationPublicKey = localStorage.getItem("authenticatedIdentity");
+    var pinCode = getPincode(authenticationPublicKey);
 
-    if(pinCode == "" || pinCode == null) {
+    if(pinCode === "" || pinCode == null) {
       loadIdentityInternal(authenticationPublicKey, "00000000").then(result => {
-        if(result.code != "200") {
-          console.log(result)
+        if(result.code !== "200") {
+          console.log(result);
           //var event = createEvent("CanNotLoadIdentity", "ErrorDuringLoadingIdentity", [authenticationPublicKey])
           //parent.onEvent(event)
-          var event = createEvent("CanNotGetPincodeForAuthenticatedIdentity", "IdentityNotLoaded", [authenticationPublicKey])
+          var event = createEvent("CanNotGetPincodeForAuthenticatedIdentity", "IdentityNotLoaded", [authenticationPublicKey]);
           parent.onEvent(event)
         }
       });
@@ -2355,77 +2305,77 @@ connection.promise.then(parent => {
       //parent.onEvent(event)
     } else {
       loadIdentityInternal(authenticationPublicKey, pinCode).then(result => {
-        if(result.code != "200") {
-          var event = createEvent("CanNotLoadIdentity", "ErrorDuringLoadingIdentity", [authenticationPublicKey])
+        if(result.code !== "200") {
+          var event = createEvent("CanNotLoadIdentity", "ErrorDuringLoadingIdentity", [authenticationPublicKey]);
           parent.onEvent(event)
         }
       });
     }
   }
 
-  var anynomousDeviceKeyEventsProcessing = false
-  var maxDeviceKeyAnonymousEventTime = 0
+  var anynomousDeviceKeyEventsProcessing = false;
+  var maxDeviceKeyAnonymousEventTime = 0;
 
-  var eventsDeviceEventsProcessing = false
-  var maxDeviceKeyEventTime = 0
+  var eventsDeviceEventsProcessing = false;
+  var maxDeviceKeyEventTime = 0;
 
-  var eventsEntityEventsProcessing = false
-  var maxEntityEventTime = 0
+  var eventsEntityEventsProcessing = false;
+  var maxEntityEventTime = 0;
 
-  var identityLoadedEvent = false
-  var identityAuthenticatedEvent = false
+  var identityLoadedEvent = false;
+  var identityAuthenticatedEvent = false;
 
   setInterval(function() {
-    if(currentlyAuthenticatedIdentity != null) {
-      var pinCode = getPincode(currentlyAuthenticatedIdentity.authentication.publicKey)
-      if(pinCode != null && pinCode != "") {
-        getIdentityFromLocalStorage(currentlyAuthenticatedIdentity.authentication.publicKey,
+    if(window.currentlyAuthenticatedIdentity != null) {
+      var pinCode = getPincode(window.currentlyAuthenticatedIdentity.authentication.publicKey);
+      if(pinCode != null && pinCode !== "") {
+        getIdentityFromLocalStorage(window.currentlyAuthenticatedIdentity.authentication.publicKey,
           pinCode, false).then((gotIdentity) => {
-          currentlyAuthenticatedIdentity = gotIdentity
+          window.currentlyAuthenticatedIdentity = gotIdentity;
           //console.log("Set loaded identity in pincode check interval")
-          currentlyLoadedIdentity = gotIdentity
+          window.currentlyLoadedIdentity = gotIdentity;
           if(identityAuthenticatedEvent === false && gotIdentity != null) {
-            var event = createEvent("IdentityAuthenticated", "Authenticated", [gotIdentity.authentication.publicKey])
-            parent.onEvent(event)
+            var event = createEvent("IdentityAuthenticated", "Authenticated", [gotIdentity.authentication.publicKey]);
+            parent.onEvent(event);
             identityAuthenticatedEvent = true
           }
         })
       } else {
-        authenticationPublicKey = localStorage.getItem("authenticatedIdentity")
+        window.authenticationPublicKey = localStorage.getItem("authenticatedIdentity");
 
-        if(authenticationPublicKey != null && authenticationPublicKey != "") {
-          /*var event = createEvent("CanNotLoadPincodeForAuthenticatedIdentity", "IdentityNotLoaded", [currentlyAuthenticatedIdentity.authentication.publicKey])
+        if(authenticationPublicKey != null && authenticationPublicKey !== "") {
+          /*var event = createEvent("CanNotLoadPincodeForAuthenticatedIdentity", "IdentityNotLoaded", [window.currentlyAuthenticatedIdentity.authentication.publicKey])
           parent.onEvent(event)
           clearPinCodeTtl(authenticationPublicKey)
-          currentlyAuthenticatedIdentity = null*/
+          window.currentlyAuthenticatedIdentity = null*/
           loadIdentityInternal(authenticationPublicKey, "00000000").then(result => {
-            if(result.code != "200") {
-              console.log(result)
-              var event = createEvent("CanNotGetPincodeForAuthenticatedIdentity", "IdentityNotLoaded", [authenticationPublicKey])
-              parent.onEvent(event)
-              clearPinCodeTtl(authenticationPublicKey)
-              currentlyAuthenticatedIdentity = null
+            if(result.code !== "200") {
+              console.log(result);
+              var event = createEvent("CanNotGetPincodeForAuthenticatedIdentity", "IdentityNotLoaded", [authenticationPublicKey]);
+              parent.onEvent(event);
+              clearPinCodeTtl(authenticationPublicKey);
+              window.currentlyAuthenticatedIdentity = null
             }
           });
         }
 
-        identityAuthenticatedEvent = false
+        identityAuthenticatedEvent = false;
         //console.log("Set loaded identity in cycle for not authenticated value")
-        currentlyLoadedIdentity = null
+        window.currentlyLoadedIdentity = null
       }
     }
 
-    if(currentlyLoadedIdentity != null) {
-      var pinCode = getPincode(currentlyLoadedIdentity.authentication.publicKey)
-      if(pinCode == "" || pinCode == null) {
+    if(window.currentlyLoadedIdentity != null) {
+      var pinCode = getPincode(window.currentlyLoadedIdentity.authentication.publicKey);
+      if(pinCode === "" || pinCode == null) {
         if(identityLoadedEvent === false) {
-          /*var event = createEvent("CanNotLoadPincodeForLoadedIdentity", "IdentityNotLoaded", [currentlyLoadedIdentity.authentication.publicKey])
+          /*var event = createEvent("CanNotLoadPincodeForLoadedIdentity", "IdentityNotLoaded", [window.currentlyLoadedIdentity.authentication.publicKey])
           parent.onEvent(event)
           identityLoadedEvent = true*/
-          loadIdentityInternal(currentlyLoadedIdentity.authentication.publicKey, "00000000").then(result => {
-            if(result.code != "200") {
-              var event = createEvent("CanNotLoadPincodeForLoadedIdentity", "IdentityNotLoaded", [currentlyLoadedIdentity.authentication.publicKey])
-              parent.onEvent(event)
+          loadIdentityInternal(window.currentlyLoadedIdentity.authentication.publicKey, "00000000").then(result => {
+            if(result.code !== "200") {
+              var event = createEvent("CanNotLoadPincodeForLoadedIdentity", "IdentityNotLoaded", [window.currentlyLoadedIdentity.authentication.publicKey]);
+              parent.onEvent(event);
               identityLoadedEvent = true
             }
           });
@@ -2436,53 +2386,44 @@ connection.promise.then(parent => {
     }
 
 
-    if (currentlyAuthenticatedIdentity != null) {
-      var now = new Date().getTime()
-      if(now - lastTimeGetProfile > 30000) {
-        var identityToStore = currentlyAuthenticatedIdentity
+    if (window.currentlyAuthenticatedIdentity != null) {
+      var now = new Date().getTime();
+      if(now - window.lastTimeGetProfile > 30000) {
+        var identityToStore = window.currentlyAuthenticatedIdentity;
         getProfileData(identityToStore).then(executeResult => {
-          console.log("Profile updated in cycle")
+          console.log("Profile updated in cycle");
           console.log(executeResult)
         });
-        lastTimeGetProfile = now
+        window.lastTimeGetProfile = now
       }
     }
-  }, 50)
+  }, 50);
 
   setInterval(function() {
 
-    if (currentlyLoadedIdentity != null && anynomousDeviceKeyEventsProcessing == false) {
-      anynomousDeviceKeyEventsProcessing = true
-      executeRestfulFunction("public", viamAnonymousApi, viamAnonymousApi.eventGetNewEventsWithoutSession, "devicekey").then(executeResult => {
-        if(executeResult.code == "200") {
-          var eventsLen = executeResult.data.length
-          changedMaxDeviceKeyAnonymousEventTime = false
-          for(var i = 0; i < eventsLen; i++) {
-            var event = executeResult.data[i]
+    if (window.currentlyLoadedIdentity != null && anynomousDeviceKeyEventsProcessing === false) {
+      anynomousDeviceKeyEventsProcessing = true;
+      executeRestfulFunction("public", viamAnonymousApi, viamAnonymousApi.eventGetNewEventsWithoutSession, "devicekey").then(async executeResult => {
+        if(executeResult.code === "200") {
+          var eventsLen = executeResult.data.length;
+          let changedMaxDeviceKeyAnonymousEventTime = false;
+          for (var i = 0; i < eventsLen; i++) {
+            var event = executeResult.data[i];
             //console.log("Received event anynomous: " + event)
-            switch(event.type) {
+            switch (event.type) {
               case "Authenticated" : {
-                console.log("Sending authenticated event")
-                var uuid = event.payloads[0]
-                var token = event.payloads[1]
-                viamApi.setSessionData(uuid, token)
-                localStorage.setItem("uuid", uuid)
-                localStorage.setItem("token", token)
-                localStorage.setItem("authenticatedIdentity",
-                  currentlyLoadedIdentity.authentication.publicKey)
-                setKeyForUUID(uuid, currentlyLoadedIdentity.authentication.publicKey)
-
-                currentlyAuthenticatedIdentity = currentlyLoadedIdentity
-                lastTimeGetProfile = 0;
-
-                var identityToStore = currentlyAuthenticatedIdentity
+                console.log("Sending authenticated event");
+                const uuid = event.payloads[0];
+                const token = event.payloads[1];
+                await handleIdentityLogin(window.currentlyLoadedIdentity, uuid, token);
+                const identityToStore = window.currentlyAuthenticatedIdentity;
                 event.payloads = [{fromQRCode: true}];
-                console.log(identityToStore)
+                console.log(identityToStore);
                 setIdentityInLocalStorage(identityToStore).then(() => {
-                  console.log(identityToStore)
+                  console.log(identityToStore);
                   getProfileData(identityToStore).then(executeResult2 => {
-                    console.log("Profile updated in setInterval function")
-                    console.log(executeResult2)
+                    console.log("Profile updated in setInterval function");
+                    console.log(executeResult2);
                     parent.onEvent(event)
                   });
                 });
@@ -2490,31 +2431,31 @@ connection.promise.then(parent => {
               }
 
               case "QRCodeUpdated" : {
-                var actionID = event["actionID"]
-                var QrCode = event["payloads"][1]
+                var actionID = event["actionID"];
+                var QrCode = event["payloads"][1];
 
-                var eventCopy = JSON.parse(JSON.stringify(event))
+                var eventCopy = JSON.parse(JSON.stringify(event));
 
                 QRCode.toDataURL(actionID + "," + QrCode, function (err, url) {
-                  eventCopy["payloads"].push(url)
+                  eventCopy["payloads"].push(url);
                   parent.onEvent(eventCopy)
-                })
+                });
                 break
               }
 
               case "KeyDeleted" : {
-                authenticationPublicKey = localStorage.getItem("authenticatedIdentity")
-                clearPinCodeTtl(authenticationPublicKey)
-                localStorage.removeItem("uuid")
-                localStorage.removeItem("token")
-                localStorage.removeItem("authenticatedIdentity")
-                delete loadedIdentities[authenticationPublicKey]
+                window.authenticationPublicKey = localStorage.getItem("authenticatedIdentity");
+                clearPinCodeTtl(authenticationPublicKey);
+                localStorage.removeItem("uuid");
+                localStorage.removeItem("token");
+                localStorage.removeItem("authenticatedIdentity");
+                delete window.loadedIdentities[authenticationPublicKey];
                 //console.log("Set loaded identity in key deleted")
-                currentlyLoadedIdentity = null
-                currentlyAuthenticatedIdentity = null
-                lastTimeGetProfile = 0;
+                window.currentlyLoadedIdentity = null;
+                window.currentlyAuthenticatedIdentity = null;
+                window.lastTimeGetProfile = 0;
 
-                destroyIdentityFromLocalStorage(authenticationPublicKey)
+                destroyIdentityFromLocalStorage(authenticationPublicKey);
                 break
               }
 
@@ -2522,7 +2463,7 @@ connection.promise.then(parent => {
                 parent.onEvent(event)
               }
             }
-            changedMaxDeviceKeyAnonymousEventTime = true
+            changedMaxDeviceKeyAnonymousEventTime = true;
             maxDeviceKeyAnonymousEventTime = Math.max(maxDeviceKeyAnonymousEventTime, event.stamp)
           }
 
@@ -2542,27 +2483,27 @@ connection.promise.then(parent => {
       });
     }
 
-    /*if(currentlyAuthenticatedIdentity === null) {
+    /*if(window.currentlyAuthenticatedIdentity === null) {
         console.log("Currently authenticated identity is null")
     }*/
 
-    if (currentlyAuthenticatedIdentity != null && eventsDeviceEventsProcessing == false) {
-      eventsDeviceEventsProcessing = true
+    if (window.currentlyAuthenticatedIdentity != null && eventsDeviceEventsProcessing === false) {
+      eventsDeviceEventsProcessing = true;
       executeRestfulFunction("private", viamApi, viamApi.eventGetNewEvents, "devicekey").then(executeResult => {
-        if(executeResult.code == "200") {
-          var eventsLen = executeResult.data.length
-          changedMaxDeviceKeyEventTime = false
+        if(executeResult.code === "200") {
+          var eventsLen = executeResult.data.length;
+          const changedMaxDeviceKeyEventTime = false;
           for(var i = 0; i < eventsLen; i++) {
-            var event = executeResult.data[i]
+            var event = executeResult.data[i];
             //console.log("Received event device key: " + event)
-            if(event.type == "QRCodeUpdated") {
-              var actionID = event["actionID"]
-              var QrCode = event["payloads"][1]
+            if(event.type === "QRCodeUpdated") {
+              var actionID = event["actionID"];
+              var QrCode = event["payloads"][1];
 
-              var eventCopy = JSON.parse(JSON.stringify(event))
+              var eventCopy = JSON.parse(JSON.stringify(event));
 
               QRCode.toDataURL(actionID + "," + QrCode, function (err, url) {
-                eventCopy["payloads"].push(url)
+                eventCopy["payloads"].push(url);
                 parent.onEvent(eventCopy)
               })
             } else {
@@ -2586,31 +2527,31 @@ connection.promise.then(parent => {
       });
     }
 
-    if (currentlyAuthenticatedIdentity != null && eventsEntityEventsProcessing == false) {
-      eventsEntityEventsProcessing = true
+    if (window.currentlyAuthenticatedIdentity != null && eventsEntityEventsProcessing === false) {
+      eventsEntityEventsProcessing = true;
       executeRestfulFunction("private", viamApi, viamApi.eventGetNewEvents, "entity").then(executeResult => {
-        if(executeResult.code == "200") {
-          var eventsLen = executeResult.data.length
-          changedMaxEntityEventTime = false
+        if(executeResult.code === "200") {
+          var eventsLen = executeResult.data.length;
+          let changedMaxEntityEventTime = false;
           for(var i = 0; i < eventsLen; i++) {
-            event = executeResult.data[i]
-            if(event.type == "QRCodeUpdated") {
-              var actionID = event["actionID"]
-              var QrCode = event["payloads"][1]
+            event = executeResult.data[i];
+            if(event.type === "QRCodeUpdated") {
+              var actionID = event["actionID"];
+              var QrCode = event["payloads"][1];
 
-              var eventCopy = JSON.parse(JSON.stringify(event))
+              var eventCopy = JSON.parse(JSON.stringify(event));
 
               QRCode.toDataURL(actionID + "," + QrCode, function (err, url) {
-                eventCopy["payloads"].push(url)
+                eventCopy["payloads"].push(url);
                 parent.onEvent(eventCopy)
-              })
+              });
 
               continue
             }
 
             //console.log("Received event entity: " + event)
-            parent.onEvent(event)
-            changedMaxEntityEventTime = true
+            parent.onEvent(event);
+            changedMaxEntityEventTime = true;
             //console.log(maxEntityEventTime + " " + event.stamp)
             maxEntityEventTime = Math.max(maxEntityEventTime, event.stamp)
           }
diff --git a/javascript/src/iframe/wopiapi-iframe.js b/javascript/src/iframe/wopiapi-iframe.js
index d1a10ff9abccd5340dd86b0fac317ce977b642f6..bb3b66446ede955839e38528035035f962a4ae5b 100644
--- a/javascript/src/iframe/wopiapi-iframe.js
+++ b/javascript/src/iframe/wopiapi-iframe.js
@@ -2,21 +2,21 @@ const axios = require('axios');
 
 function WopiAPI() {}
 
-WopiAPI.prototype.getPassports = function(fileID) {
+WopiAPI.prototype.getPassports = function (fileID) {
   const requestConfig = {
     headers: {
-      'publicKey': viamApi.getConfig().headers.publicKey,
-      'uuid': viamApi.getConfig().headers.uuid,
-      'token': viamApi.getConfig().headers.token,
-      'fileID': fileID
+      publicKey: window.viamApi.getConfig().headers.publicKey,
+      uuid: window.viamApi.getConfig().headers.uuid,
+      token: window.viamApi.getConfig().headers.token,
+      deviceHash: window.viamApi.getConfig().headers.deviceHash,
+      userAgent: window.viamApi.getConfig().headers.userAgent,
+      fileID
     }
   };
 
   const [protocol, host] = window.API_HOST.split(':');
 
   const url = `${protocol}${host}${window.WOPI_URI_PREFIX}/getPassports`;
-  // TODO: remove console log
-  console.log('Wopi', url);
   return axios.post(url, {}, requestConfig);
 };
 
diff --git a/javascript/src/utilities/appUtility.js b/javascript/src/utilities/appUtility.js
new file mode 100644
index 0000000000000000000000000000000000000000..00beb2568a03ec3070308acb63d2aee14e262c42
--- /dev/null
+++ b/javascript/src/utilities/appUtility.js
@@ -0,0 +1,12 @@
+import { getCrypto } from 'pkijs';
+
+export const createDeviceHash = async (publicKey) => {
+  try {
+    const stringToEncode = publicKey + navigator.userAgent;
+    const crypto = getCrypto();
+    const buffer = new window.TextEncoder("utf-8").encode(stringToEncode);
+    return window.btoa(await crypto.digest({ name: "SHA-1" }, buffer));
+  } catch (error) {
+    console.warn(error); // eslint-disable-line no-console
+  }
+};
diff --git a/main.go b/main.go
index 49dbcddc017c5f667fcc55771f59f05c3727cf20..cc9cd0802f88ab2b59a16d44163e13966f40afd5 100644
--- a/main.go
+++ b/main.go
@@ -73,18 +73,23 @@ func buildViamAPI() string {
 		"        headers: {\n" +
 		"            'publicKey': '',\n" +
 		"            'uuid': '',\n" +
+		"            'deviceHash': '',\n" +
+		"            'userAgent': '',\n" +
 		"            'token': ''\n" +
 		"        }\n" +
 		"    }\n" +
 		"}\n\n"
 
-	result += "ViamAPI.prototype.setSessionData = function(uuid, token) {\n" +
-		"    this.config.headers.uuid = \" \" + uuid;\n" +
-		"    this.config.headers.token = \" \" + token;\n" +
+
+	result += "ViamAPI.prototype.setSessionData = function(uuid, token, deviceHash, userAgent) {\n" +
+		"    this.config.headers.uuid = uuid;\n" +
+		"    this.config.headers.token = token;\n" +
+		"    this.config.headers.deviceHash = deviceHash;\n" +
+		"    this.config.headers.userAgent = userAgent;\n" +
 		"};\n\n"
 
 	result += "ViamAPI.prototype.setIdentity = function(authenticationPublicKey) {\n" +
-		"    this.config.headers.publicKey = \" \" + window.btoa(authenticationPublicKey);\n" +
+		"    this.config.headers.publicKey = window.btoa(authenticationPublicKey);\n" +
 		"};\n\n"
 
 	result += "ViamAPI.prototype.getConfig = function() {\n" +