const system = require('../../system');
const uuidv4 = require('uuid/v4');
class AuthUtils {
  constructor() {
    this.cacheManager = system.getObject('db.common.cacheManager');
    this.exTime = 5 * 3600;// 缓存过期时间，5小时
  }
  getUUID() {
    const uuid = uuidv4();
    const u = uuid.replace(/-/g, '');
    return u;
  }
  /**
     * 获取访问token信息
     * @param {*} appkey 应用key
     * @param {*} secret 应用密钥
     */
  async getTokenInfo(appkey, secret) {
    let rtnKey = this.getUUID();
    const cacheAccessKey = await this.cacheManager.ApiAccessKeyCache.cache(appkey, rtnKey, this.exTime);
    if (cacheAccessKey) {
      rtnKey = cacheAccessKey.accessKey;
    }// 获取之前的token值
    const appData = await this.cacheManager.ApiAccessKeyCache.cache(rtnKey, secret, this.exTime, appkey);
    if (!appData) {
      return system.getResultFail(system.getAppInfoFail, 'key或secret错误.');
    }
    if (!appData.isEnabled) {
      return system.getResultFail(system.waitAuditApp, '应用处于待审核等待启用状态.');
    }
    appData.accessKey = rtnKey;
    return system.getResultSuccess(appData);
  }
}

module.exports = AuthUtils;
