Skip to content
Snippets Groups Projects
viamapi-iframe.js 88.9 KiB
Newer Older
  • Learn to ignore specific revisions
  •         })
          });
        },
        getCertificateByPassport(passportUUID) {
          return new Penpal.Promise(result => {
            authenticationPublicKey = localStorage.getItem("authenticatedIdentity")
            if (authenticationPublicKey === null) {
              return {"data" : "",
                "code" : "400",
                "status" : "Identity not loaded"
              }
            }
            if (loadedIdentities[authenticationPublicKey] === null) {
              return {"data" : "",
                "code" : "400",
                "status" : "Identity not loaded"
              }
            }
    
            var success = extendPinCodeTtl(authenticationPublicKey)
    
            if(success == false) {
              result({"data" : "",
                "code" : "400",
                "status" : "Identity not authenticated"
              })
            }
    
            getCertificateForPassport(passportUUID, false).then(certificateResult => {
              //console.log(certificateResult)
              result(certificateResult)
            })
          });
        },
        getOneTimeCertificateByPassport(passportUUID, emailArg) {
          return new Penpal.Promise(result => {
            authenticationPublicKey = localStorage.getItem("authenticatedIdentity")
            if (authenticationPublicKey === null) {
              return {"data" : "",
                "code" : "400",
                "status" : "Identity not loaded"
              }
            }
            if (loadedIdentities[authenticationPublicKey] === null) {
              return {"data" : "",
                "code" : "400",
                "status" : "Identity not loaded"
              }
            }
    
            var success = extendPinCodeTtl(authenticationPublicKey)
    
            if(success == false) {
              result({"data" : "",
                "code" : "400",
                "status" : "Identity not authenticated"
              })
            }
    
            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"]
    
                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 oneTimeCryptoData = new CryptoData();
                  oneTimeCryptoData.setx509Certificate(certificateOneTime)
                  oneTimeCryptoData.setPrivateKey(privateKeyOneTime)
                  oneTimeCryptoData.setPublicKey(publicKeyOneTime)
                  oneTimeCryptoData.setChain(passportChain)
    
                  result({"data" : oneTimeCryptoData,
                    "code" : "200",
                    "status" : "One time certificate generated"
                  })
                  // Prints PEM formatted signed certificate
                  // -----BEGIN CERTIFICATE-----MIID....7Hyg==-----END CERTIFICATE-----
    
                });
              } else {
                result({"data" : "",
                  "code" : "400",
                  "status" : "Can not generate one time certificate"
                })
              }
            })
          });
        },
        signEmail(passportUUID, emailArg, emailMessage) {
          return new Penpal.Promise(result => {
            authenticationPublicKey = localStorage.getItem("authenticatedIdentity")
            if (authenticationPublicKey === null) {
              return {"data" : "",
                "code" : "400",
                "status" : "Identity not authenticated"
              }
            }
            if (loadedIdentities[authenticationPublicKey] === null) {
              return {"data" : "",
                "code" : "400",
                "status" : "Identity not authenticated"
              }
            }
    
            var success = extendPinCodeTtl(authenticationPublicKey)
    
            if(success == false) {
              result({"data" : "",
                "code" : "400",
                "status" : "Identity not authenticated"
              })
            }
    
            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"]
    
                createOneTimePassportCertificate(makeid() + "-" + passportUUID, emailArg, passportPrivateKey, passportCertificate).then(function(keys){
                  var publicKeyOneTime = keys["publicKeyPEM"]
                  var privateKeyOneTime = keys["privateKeyPEM"]
                  var certificateOneTime = keys["certificatePEM"]
                  //download("certificateOneTime.crt", "text/plain", certificateOneTime)
    
                  passportChain.push(passportCertificate)
    
                  //console.log("Before sign email")
                  //console.log(certificateOneTime)
                  //console.log(passportChain)
                  //console.log(privateKeyOneTime)
    
                  executeRestfulFunction("private", viamApi, viamApi.passportGetEmailWithHeaderByPassport,
    
                    passportUUID, emailMessage).then(executeResult2 => {
                    var emailWithHeader = executeResult2.data
    
                    //console.log(emailWithHeader)
                    //download("withheader.eml", "message/rfc822", emailWithHeader)
                    var signedEmailPromise = signEmail(emailWithHeader,
                      certificateOneTime,
                      passportChain,
                      privateKeyOneTime)
    
                    signedEmailPromise.then(signedEmail => {
                      executeRestfulFunction("private", viamApi, viamApi.signResignEmail,
    
                        passportUUID, signedEmail).then(executeResult => {
                        result({"data" : executeResult.data,
    
                          "code" : "200",
                          "status" : "Email signed"
                        })
                      });
                      /*result({"data" : signedEmail,
                          "code" : "200",
                          "status" : "Email signed"
                      })*/
                    });
                  });
                  // Prints PEM formatted signed certificate
                  // -----BEGIN CERTIFICATE-----MIID....7Hyg==-----END CERTIFICATE-----
    
                });
              } else {
                result({"data" : "",
                  "code" : "400",
                  "status" : "Can not sign email"
                })
              }
            })
          });
        },
        hasSession() {
          return new Penpal.Promise(result => {
            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"
              });
            }
    
            var success = extendPinCodeTtl(authenticationPublicKey)
    
            if(success == false) {
              result({"data" : "",
                "code" : "400",
                "status" : "Identity not authenticated"
              })
            }
    
            executeRestfulFunction("private", viamApi, viamApi.identityHasSession).then(executeResult => {
              result(executeResult);
            });
          });
        },
        marketingSignUpIdentificator(identificator, reference) {
          return new Penpal.Promise(result => {
            viamApi.setIdentity("marketingapppublickey")
    
            executeRestfulFunction("public", viamApi, viamApi.marketingSignUpIdentificator, identificator, reference).then(executeResult => {
              viamApi.setIdentity("")
              viamApi.setSessionData("", "")
              result(executeResult);
            });
          });
        },
        marketingGetIdentificatorProfile(identificator, pincode) {
          return new Penpal.Promise(result => {
            viamApi.setIdentity("marketingapppublickey")
    
            executeRestfulFunction("public", viamApi, viamApi.marketingGetIdentificatorProfile, identificator, pincode).then(executeResult => {
              viamApi.setIdentity("")
              viamApi.setSessionData("", "")
              result(executeResult);
            });
          });
        },
    
        marketingExecuteEventForIdentificator(identificator, pincode, event) {
    
          return new Penpal.Promise(result => {
            viamApi.setIdentity("marketingapppublickey")
    
            executeRestfulFunction("public", viamApi, viamApi.marketingExecuteEventForIdentificator, identificator, pincode, event).then(executeResult => {
              viamApi.setIdentity("")
              viamApi.setSessionData("", "")
              result(executeResult);
            });
          });
        },
        getCurrentlyAuthenticatedIdentity() {
          return new Penpal.Promise(result => {
            result({"data" : currentlyAuthenticatedIdentity,
              "code" : "200",
              "status" : "Currently authenticated identity"
            })
          });
        },
    
        stringToUtf8ByteArray(str) {
          if (typeof str !== 'string') {
            str = str.toString()
          }
          let res = Buffer.from(str,'utf-8')
          return new Penpal.Promise(result => {
            result(res)
          })
        },
        utf8ByteArrayToString(ba) {
          if (!Buffer.isBuffer(ba)) {
            ba = Buffer.from(ba)
          }
          let res = ba.toString('utf-8')
          return new Penpal.Promise(result => {
            result(res)
          })
        },
        stringToUtf8Base64(str) {
          if (!Buffer.isBuffer(str)) {
            if (typeof str !== 'string') {
              str = str.toString()
            }
            str = Buffer.from(str, 'utf-8')
          }
          let res = str.toString('base64')
          return new Penpal.Promise(result => {
            result(res)
          })
        },
        utf8Base64ToString(strBase64) {
          if (!Buffer.isBuffer(strBase64)) {
            if (typeof strBase64 !== 'string') {
              strBase64 = strBase64.toString()
            }
            strBase64 = Buffer.from(strBase64, 'base64')
          }
          let res = strBase64.toString('utf-8')
          return new Penpal.Promise(result => {
            result(res)
          })
        },
        base64ToByteArray(strBase64) {
          if (typeof strBase64 !== 'string') {
            strBase64 = strBase64.toString()
          }
          let res = Buffer.from(strBase64, 'base64')
          return new Penpal.Promise(result => {
            result(res)
          })
        },
        byteArrayToBase64(ba) {
          if (!Buffer.isBuffer(ba)) {
            ba = Buffer.from(ba)
          }
          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])
          parent.onEvent(event)
        }
      });
    
    
      var identities = localStorage.getItem("identities")
    
      console.log("Library loaded at: " + new Date().toISOString())
    
      if (identities === "" || identities === null) {
        //console.log("Setting up empty version")
        localStorage.setItem("identities", JSON.stringify({}))
      }
    
      if (localStorage.getItem("uuid") === null || localStorage.getItem("token") === null
        || localStorage.getItem("authenticatedIdentity") === null) {
        localStorage.removeItem("uuid")
        localStorage.removeItem("token")
        localStorage.removeItem("authenticatedIdentity")
      } else {
        authenticationPublicKey = localStorage.getItem("authenticatedIdentity")
        var pinCode = getPincode(authenticationPublicKey)
    
        if(pinCode == "" || pinCode == null) {
          loadIdentityInternal(authenticationPublicKey, "00000000").then(result => {
            if(result.code != "200") {
              console.log(result)
              //var event = createEvent("CanNotLoadIdentity", "ErrorDuringLoadingIdentity", [authenticationPublicKey])
              //parent.onEvent(event)
              var event = createEvent("CanNotGetPincodeForAuthenticatedIdentity", "IdentityNotLoaded", [authenticationPublicKey])
              parent.onEvent(event)
            }
          });
          //var event = createEvent("CanNotGetPincodeForAuthenticatedIdentity", "IdentityNotLoaded", [authenticationPublicKey])
          //parent.onEvent(event)
        } else {
          loadIdentityInternal(authenticationPublicKey, pinCode).then(result => {
            if(result.code != "200") {
              var event = createEvent("CanNotLoadIdentity", "ErrorDuringLoadingIdentity", [authenticationPublicKey])
              parent.onEvent(event)
            }
          });
        }
      }
    
      var anynomousDeviceKeyEventsProcessing = false
      var maxDeviceKeyAnonymousEventTime = 0
    
      var eventsDeviceEventsProcessing = false
      var maxDeviceKeyEventTime = 0
    
      var eventsEntityEventsProcessing = false
      var maxEntityEventTime = 0
    
      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,
              pinCode, false).then((gotIdentity) => {
              currentlyAuthenticatedIdentity = gotIdentity
              //console.log("Set loaded identity in pincode check interval")
              currentlyLoadedIdentity = gotIdentity
              if(identityAuthenticatedEvent === false && gotIdentity != null) {
                var event = createEvent("IdentityAuthenticated", "Authenticated", [gotIdentity.authentication.publicKey])
                parent.onEvent(event)
                identityAuthenticatedEvent = true
              }
            })
          } else {
            authenticationPublicKey = localStorage.getItem("authenticatedIdentity")
    
            if(authenticationPublicKey != null && authenticationPublicKey != "") {
              /*var event = createEvent("CanNotLoadPincodeForAuthenticatedIdentity", "IdentityNotLoaded", [currentlyAuthenticatedIdentity.authentication.publicKey])
              parent.onEvent(event)
              clearPinCodeTtl(authenticationPublicKey)
              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
                }
              });
            }
    
            identityAuthenticatedEvent = false
            //console.log("Set loaded identity in cycle for not authenticated value")
            currentlyLoadedIdentity = null
          }
        }
    
        if(currentlyLoadedIdentity != null) {
          var pinCode = getPincode(currentlyLoadedIdentity.authentication.publicKey)
          if(pinCode == "" || pinCode == null) {
            if(identityLoadedEvent === false) {
              /*var event = createEvent("CanNotLoadPincodeForLoadedIdentity", "IdentityNotLoaded", [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)
                  identityLoadedEvent = true
                }
              });
            }
          } else {
            identityLoadedEvent = false
          }
        }
    
    
        if (currentlyAuthenticatedIdentity != null) {
          var now = new Date().getTime()
          if(now - lastTimeGetProfile > 30000) {
            var identityToStore = currentlyAuthenticatedIdentity
            getProfileData(identityToStore).then(executeResult => {
              console.log("Profile updated in cycle")
              console.log(executeResult)
            });
            lastTimeGetProfile = now
          }
        }
      }, 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]
                //console.log("Received event anynomous: " + event)
                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
    
                    event.payloads = [{fromQRCode: true}];
    
                    console.log(identityToStore)
                    setIdentityInLocalStorage(identityToStore).then(() => {
                      console.log(identityToStore)
                      getProfileData(identityToStore).then(executeResult2 => {
                        console.log("Profile updated in setInterval function")
                        console.log(executeResult2)
                        parent.onEvent(event)
                      });
                    });
                    break;
                  }
    
                  case "QRCodeUpdated" : {
                    var actionID = event["actionID"]
                    var QrCode = event["payloads"][1]
    
                    var eventCopy = JSON.parse(JSON.stringify(event))
    
                    QRCode.toDataURL(actionID + "," + QrCode, function (err, 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]
                    //console.log("Set loaded identity in key deleted")
                    currentlyLoadedIdentity = null
                    currentlyAuthenticatedIdentity = null
                    lastTimeGetProfile = 0;
    
                    destroyIdentityFromLocalStorage(authenticationPublicKey)
                    break
                  }
    
                  default : {
                    parent.onEvent(event)
                  }
                }
                changedMaxDeviceKeyAnonymousEventTime = true
                maxDeviceKeyAnonymousEventTime = Math.max(maxDeviceKeyAnonymousEventTime, event.stamp)
              }
    
              if(changedMaxDeviceKeyAnonymousEventTime) {
                //console.log("Updating max time anonymous device with " + maxDeviceKeyAnonymousEventTime )
                executeRestfulFunction("public", viamAnonymousApi, viamAnonymousApi.eventUpdateLastViewedWithoutSession,
                  "devicekey", maxDeviceKeyAnonymousEventTime.toString()).then(executeResult1 => {
                  anynomousDeviceKeyEventsProcessing = false
                })
              } else {
                anynomousDeviceKeyEventsProcessing = false
              }
            } else {
              anynomousDeviceKeyEventsProcessing = false
              //console.log("Error during query anynomous device")
            }
          });
        }
    
        /*if(currentlyAuthenticatedIdentity === null) {
            console.log("Currently authenticated identity is null")
        }*/
    
        if (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
              for(var i = 0; i < eventsLen; 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]
    
                  var 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) {
                //console.log("Updating max time authenticated device")
                executeRestfulFunction("private", viamApi, viamApi.eventUpdateLastViewed, "devicekey",
                  maxDeviceKeyEventTime.toString()).then(executeResult1 => {
                  eventsDeviceEventsProcessing = false
                })
              } else {
                eventsDeviceEventsProcessing = false
              }
            } else {
              //console.log("Error during query device")
              eventsDeviceEventsProcessing = false
            }
          });
        }
    
        if (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
              for(var i = 0; i < eventsLen; i++) {
                event = executeResult.data[i]
                if(event.type == "QRCodeUpdated") {
                  var actionID = event["actionID"]
                  var QrCode = event["payloads"][1]
    
                  var eventCopy = JSON.parse(JSON.stringify(event))
    
                  QRCode.toDataURL(actionID + "," + QrCode, function (err, url) {
                    eventCopy["payloads"].push(url)
                    parent.onEvent(eventCopy)
                  })
    
                  continue
                }
    
                //console.log("Received event entity: " + event)
                parent.onEvent(event)
                changedMaxEntityEventTime = true
                //console.log(maxEntityEventTime + " " + event.stamp)
                maxEntityEventTime = Math.max(maxEntityEventTime, event.stamp)
              }
              if(changedMaxEntityEventTime) {
                //console.log("Updating max time entity" + maxEntityEventTime)
                executeRestfulFunction("private", viamApi, viamApi.eventUpdateLastViewed, "entity",
                  maxEntityEventTime.toString()).then(executeResult1 => {
                  eventsEntityEventsProcessing = false
                })
              } else {
                eventsEntityEventsProcessing = false
              }
            } else {
              //console.log("Error during query entity")
              eventsEntityEventsProcessing = false
            }
          });
        }
      }, 1000);
    });