UNPKG

sns-login-sdk

Version:

统一身份登录 SDK - 基于自定义协议调用桌面应用程序进行身份认证

2 lines (1 loc) 2.49 kB
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var t=require("uuid");class i{constructor(t={}){const{options:i={},callbacks:s={}}=t;this.options={pollingTimeout:6e5,pollingInterval:1e3,baseURL:"http://localhost:3500",apiEndpoints:{getVp:"/get/vp"},baseUrl:"undefined"!=typeof window?window.location.origin:"",type:1,...i},this.uuidString="",this.startTime=0,this.isPolling=!1,this.pollingTimer=null,this.callbacks={onLoading:t=>{},onSuccess:t=>{},onError:t=>{},onMessage:(t,i="info")=>{},...s},this.login=this.login.bind(this),this.stopPolling=this.stopPolling.bind(this)}async login(){try{this.uuidString=t.v7().slice(0,32),this.callbacks.onLoading(!0),await this.invokeDesktopApp()}catch(t){this.callbacks.onError(t),this.callbacks.onLoading(!1)}}async invokeDesktopApp(){try{const t=this.uuidString.substring(0,32),i=`tdid://getVP?json=${JSON.stringify({uuid:t,baseUrl:this.options.baseUrl,type:this.options.type})}`,s=document.createElement("iframe");s.style.display="none",s.src=i,document.body.appendChild(s),setTimeout(()=>{document.body.removeChild(s)},1e3),this.startPolling()}catch(t){this.callbacks.onError(t),this.callbacks.onLoading(!1)}}startPolling(){this.startTime=Date.now(),this.isPolling=!0,this.waitForVP()}async waitForVP(){if(this.isPolling){if(Date.now()-this.startTime>=this.options.pollingTimeout)return this.stopPolling(),this.callbacks.onMessage("获取签名失败","error"),void this.callbacks.onLoading(!1);try{const t=await this.apiGetVp(this.uuidString);if(t){if("refuse"===t)return this.stopPolling(),this.callbacks.onMessage("客户端正忙,请稍后再试","error"),void this.callbacks.onLoading(!1);let i=null;if(t?.tokenValue?i=t.tokenValue:t?.data?.tokenValue&&(i=t.data.tokenValue),i)return this.stopPolling(),this.callbacks.onSuccess(i),void this.callbacks.onLoading(!1)}this.pollingTimer=setTimeout(()=>{this.waitForVP()},this.options.pollingInterval)}catch(t){this.pollingTimer=setTimeout(()=>{this.waitForVP()},this.options.pollingInterval)}}}stopPolling(){this.isPolling=!1,this.pollingTimer&&(clearTimeout(this.pollingTimer),this.pollingTimer=null)}async apiGetVp(t){const i=`${this.options.baseURL}${this.options.apiEndpoints.getVp}?uuid=${t}`,s=await fetch(i,{method:"GET",headers:{"Content-Type":"application/json"}});if(!s.ok)throw new Error(`HTTP error! status: ${s.status}`);return s.json()}destroy(){this.stopPolling(),this.callbacks={}}}exports.createSnsLogin=function(t={}){return new i(t)},exports.default=i;