"use strict";vare,t=(e=require("crypto"))&&"object"==typeofe&&"default"ine?e.default:e;constn={TOKEN_EXPIRED:"uni-id-token-expired",CHECK_TOKEN_FAILED:"uni-id-check-token-failed",PARAM_REQUIRED:"uni-id-param-required",ACCOUNT_EXISTS:"uni-id-account-exists",ACCOUNT_NOT_EXISTS:"uni-id-account-not-exists",ACCOUNT_CONFLICT:"uni-id-account-conflict",ACCOUNT_BANNED:"uni-id-account-banned",ACCOUNT_AUDITING:"uni-id-account-auditing",ACCOUNT_AUDIT_FAILED:"uni-id-account-audit-failed",ACCOUNT_CLOSED:"uni-id-account-closed"};functioni(e){return!!e&&("object"==typeofe||"function"==typeofe)&&"function"==typeofe.then}functionr(e){if(!e)return;constt=e.match(/^(\d+).(\d+).(\d+)/);returnt?t.slice(1,4).map(e=>parseInt(e)):void0}functiono(e,t){constn=r(e),i=r(t);returnn?i?function(e,t){constn=Math.max(e.length,t.length);for(leti=0;i<n;i++){constn=e[i],r=t[i];if(n>r)return1;if(n<r)return-1}return0}(n,i):1:i?-1:0}consts={"uni-id-token-expired":30203,"uni-id-check-token-failed":30202};functionc(e){const{errCode:t,errMsgValue:n}=e;e.errMsg=this._t(t,n),tins&&(e.code=s[t]),deletee.errMsgValue}functiona(e){return"object"===(i=e,Object.prototype.toString.call(i).slice(8,-1).toLowerCase())&&e.errCode&&(t=e.errCode,Object.values(n).includes(t))&&!!e.errCode;vart,i}letu={"zh-Hans":{"uni-id-token-expired":"登录状态失效,token已过期","uni-id-check-token-failed":"token校验未通过","uni-id-param-required":"缺少参数: {param}","uni-id-account-exists":"此账号已注册","uni-id-account-not-exists":"此账号未注册","uni-id-account-conflict":"用户账号冲突","uni-id-account-banned":"从账号已封禁","uni-id-account-auditing":"此账号正在审核中","uni-id-account-audit-failed":"此账号审核失败","uni-id-account-closed":"此账号已注销"},en:{"uni-id-token-expired":"The login status is invalid, token has expired","uni-id-check-token-failed":"Check token failed","uni-id-param-required":"Parameter required: {param}","uni-id-account-exists":"Account exists","uni-id-account-not-exists":"Account does not exists","uni-id-account-conflict":"User account conflict","uni-id-account-banned":"Account has been banned","uni-id-account-auditing":"Account audit in progress","uni-id-account-audit-failed":"Account audit failed","uni-id-account-closed":"Account has been closed"}};try{conste=require.resolve("uni-config-center/uni-id/lang/index.js");u=function(e,t){constn=Object.keys(e);n.push(...Object.keys(t));consti={};for(letr=0;r<n.length;r++){consto=n[r];i[o]=Object.assign({},e[o],t[o])}returni}(u,require(e))}catch(e){}vard=u;functionl(e){returne.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}functionh(e){returnJSON.parse((t=function(e){vart=4-(e=e.toString()).length%4;if(4!==t)for(varn=0;n<t;++n)e+="=";returne.replace(/-/g,"+").replace(/_/g,"/")}(e),Buffer.from(t,"base64").toString("utf-8")));vart}functionf(e){returnl((t=JSON.stringify(e),Buffer.from(t,"utf-8").toString("base64")));vart}functionp(e,n){returnl(t.createHmac("sha256",n).update(e).digest("base64"))}constk=function(e,t){if("string"!=typeofe)thrownewError("Invalid token");constn=e.split(".");if(3!==n.length)thrownewError("Invalid token");const[i,r,o]=n;if(p(i+"."+r,t)!==o)thrownewError("Invalid token");consts=h(i);if("HS256"!==s.alg||"JWT"!==s.typ)thrownewError("Invalid token");constc=h(r);if(1e3*c.exp<Date.now()){conste=newError("Token expired");throwe.name="TokenExpiredError",e}returnc},g=function(e,t,n={}){const{expiresIn:i}=n;if(!i)thrownewError("expiresIn is required");constr=parseInt(Date.now()/1e3),o={...e,iat:r,exp:r+n.expiresIn},s=f({alg:"HS256",typ:"JWT"})+"."+f(o);returns+"."+p(s,t)},I=uniCloud.database(),_=I.command,C=I.collection("uni-id-users"),T=I.collection("uni-id-roles");classm{constructor({uniId:e}={}){this.uid=null,this.userRecord=null,this.userPermission=null,this.oldToken=null,this.oldTokenPayload=null,this.uniId=e,this.config=this.uniId._getConfig(),this.clientInfo=this.uniId._clientInfo,this.checkConfig()}checkConfig(){const{tokenExpiresIn:e,tokenExpiresThreshold:t}=this.config;if(t>=e)thrownewError("Config error, tokenExpiresThreshold should be less than tokenExpiresIn");t>e/2&&console.warn(`Please check whether the tokenExpiresThreshold configuration is set too large, tokenExpiresThreshold: ${t}, tokenExpiresIn: ${e}`)}getcustomToken(){returnthis.uniId.interceptorMap.get("customToken")}isTokenInDb(e){returno(e,"1.0.10")>=0}asyncgetUserRecord(){if(this.userRecord)returnthis.userRecord;conste=awaitC.doc(this.uid).get();if(this.userRecord=e.data[0],!this.userRecord)throw{errCode:n.ACCOUNT_NOT_EXISTS};switch(this.userRecord.status){casevoid0:case0:break;case1:throw{errCode:n.ACCOUNT_BANNED};case2:throw{errCode:n.ACCOUNT_AUDITING};case3:throw{errCode:n.ACCOUNT_AUDIT_FAILED};case4:throw{errCode:n.ACCOUNT_CLOSED}}if(this.oldTokenPayload){if(this.isTokenInDb(this.oldTokenPayload.uniIdVersion)){if(-1===(this.userRecord.token||[]).indexOf(this.oldToken))throw{errCode:n.CHECK_TOKEN_FAILED}}if(this.userRecord.valid_token_date&&this.userRecord.valid_token_date>1e3*this.oldTokenPayload.iat)throw{errCode:n.TOKEN_EXPIRED}}returnthis.userRecord}asyncupdateUserRecord(e){awaitC.doc(this.uid).update(e)}asyncgetUserPermission(){if(this.userPermission)returnthis.userPermission;conste=(awaitthis.getUserRecord()).role||[];if(0===e.length)returnthis.userPermission={role:[],permission:[]},this.userPermission;if(e.includes("admin"))returnthis.userPermission={role:e,permission:[]},this.userPermission;constt=awaitT.where({role_id:_.in(e)}).get(),n=(i=t.data.reduce((e,t)=>(t.permission&&e.push(...t.permission),e),[]),Array.from(newSet(i)));vari;returnthis.userPermission={role:e,permission:n},this.userPermission}async_createToken({uid:e,role:t,permission:i}={}){if(!t||!i){conste=awaitthis.getUserPermission();t=e.role,i=e.permission}letr={uid:e,role:t,permission:i};if(this.uniId.interceptorMap.has("customToken")){constn=this.uniId.interceptorMap.get("customToken");if("function"!=typeofn)thrownewError("Invalid custom token file");r=awaitn({uid:e,role:t,permission:i})}consto=Date.now(),{tokenSecret:s,tokenExpiresIn:c,maxTokenLength:a=10}=this.config,u=g({...r,uniIdVersion:"1.0.16"},s,{expiresIn:c}),d=awaitthis.getUserRecord(),l=(d.token||[]).filter(e=>{try{constt=this._checkToken(e);if(d.valid_token_date&&d.valid_token_date>1e3*t.iat)return!1}catch(e){if(e.errCode===n.TOKEN_EXPIRED)return!1}return!0});returnl.push(u),l.length>a&&l.splice(0,l.length-a),awaitthis.updateUserRecord({last_login_ip:this.clientInfo.clientIP,last_login_date:o,token:l}),{token:u,tokenExpired:o+1e3*c}}asynccreateToken({uid:e,role:t,permission:i}={}){if(!e)throw{errCode:n.PARAM_REQUIRED,errMsgValue:{param:"uid"}};this.uid=e;const{token:r,tokenExpired:o}=awaitthis._createToken({uid:e,role:t,permission:i});return{errCode:0,token:r,tokenExpired:o}}asyncrefreshToken({token:e}={}){if(!e)throw{errCode:n.PARAM_REQUIRED,errMsgValue:{param:"token"}};this.oldToken=e;constt=this._checkToken(e);this.uid=t.uid,this.oldTokenPayload=t;const{uid:i}=t,{role:r,permission:o}=awaitthis.getUserPermission(),{token:s,tokenExpired:c}=awaitthis._createToken({uid:i,role:r,permission:o});return{errCode:0,token:s,tokenExpired:c}}_checkToken(e){const{tokenSecret:t}=this.config;leti;try{i=k(e,t)}catch(e){if("TokenExpiredError"===e.name)throw{errCode:n.TOKEN_EXPIRED};throw{errCode:n.CHECK_TOKEN_FAILED}}returni}asynccheckToken(e,{autoRefresh:t=!0}={}){if(!e)throw{errCode:n.PARAM_REQUIRED,errMsgValue:{param:"token"}};this.oldToken=e;consti=this._checkToken(e);this.uid=i.uid,this.oldTokenPayload=i;const{tokenExpiresThreshold:r}=this.config,{uid:o,role:s,permission:c}=i,a={role:s,permission:c};if(!s&&!c){const{role:e,permission:t}=awaitthis.getUserPermission();a.role=e,a.permission=t}if(!r||!t){conste={code:0,errCode:0,...i,...a};returndeletee.uniIdVersion,e}constu=Date.now();letd={};1e3*i.exp-u<1e3*r&&(d=awaitthis._createToken({uid:o}));constl={code:0,errCode:0,...i,...a,...d};returndeletel.uniIdVersion,l}}varE=Object.freeze({__proto__:null,checkToken:asyncfunction(e,{autoRefresh:t=!0}={}){returnnewm({uniId:this}).checkToken(e,{autoRefresh:t})},createToken:asyncfunction({uid:e,role:t,permission:n}={}){returnnewm({uniId:this}).createToken({uid:e,role:t,permission:n})},refreshToken:asyncfunction({token:e}={}){returnnewm({uniId:this}).refreshToken({token:e})}});constw=require("uni-config-center")({pluginId:"uni-id"});classx{constructor({context:e,clientInfo:t,config:n}={}){this._clientInfo=e?function(e){return{appId:e.APPID,platform:e.PLATFORM,locale:e.LOCALE,clientIP:e.CLIENTIP,deviceId:e.DEVICEID}}(e):t,this.config=n||this._getOriginConfig(),this.interceptorMap=newMap,w.hasFile("custom-token.js")&&this.setInterceptor("customToken",require(w.resolve("custom-token.js")));this._i18n=uniCloud.initI18n({locale:this._clientInfo.locale,fallbackLocale:"zh-Hans",messages:JSON.parse(JSON.stringify(d))}),d[this._i18n.locale]||this._i18n.setLocale("zh-Hans")}setInterceptor(e,t){this.interceptorMap.set(e,t)}_t(...e){returnthis._i18n.t(...e)}_parseOriginConfig(e){returnArray.isArray(e)?e:e[0]?Object.values(e):e}_getOriginConfig(){if(w.hasFile("config.json")){lete;try{e=w.config()}catch(e){thrownewError("Invalid uni-id config file\n"+e.message)}returnthis._parseOriginConfig(e)}try{returnthis._parseOriginConfig(require("uni-id/config.json"))}catch(e){thrownewError("Invalid uni-id config file")}}_getAppConfig(){conste=this._getOriginConfig();returnArray.isArray(e)?e.find(e=>e.dcloudAppid===this._clientInfo.appId)||e.find(e=>e.isDefaultConfig):e}_getPlatformConfig(){conste=this._getAppConfig();if(!e)thrownewError(`Config for current app (${this._clientInfo.appId}) was not found, please check your config file or client appId`);lett;switch("app-plus"===this._clientInfo.platform&&(this._clientInfo.platform="app"),"h5"===this._clientInfo.platform&&(this._clientInfo.platform="web"),this._clientInfo.platform){case"web":t="h5";break;case"app":t="app-plus"}constn=[{tokenExpiresIn:7200,tokenExpiresThreshold:1200,passwordErrorLimit:6,passwordErrorRetryTime:3600},e];t&&e[t]&&n.push(e[t]),n.push(e[this._clientInfo.platform]);consti=Object.assign(...n);return["tokenSecret","tokenExpiresIn"].forEach(e=>{if(!i||!i[e])thrownewError(`Config parameter missing, ${e} is required`)}),i}_getConfig(){returnthis._getPlatformConfig()}}for(consteinE)x.prototype[e]=E[e];functiony(e){constt=newx(e);returnnewProxy(t,{get(e,t){if(tine&&0!==t.indexOf("_")){if("function"==typeofe[t])return(n=e[t],function(){lete;try{e=n.apply(this,arguments)}catch(e){if(a(e))returnc.call(this,e),e;throwe}returni(e)?e.then(e=>(a(e)&&c.call(this,e),e),e=>{if(a(e))returnc.call(this,e),e;throwe}):(a(e)&&c.call(this,e),e)}).bind(e);if("context"!==t&&"config"!==t)returne[t]}varn}})}x.prototype.createInstance=y;constA={createInstance:y};module.exports=A;