@mamba-le/auth
Version:
1,561 lines (1,360 loc) • 42.6 kB
JavaScript
/**
* @description 认证模块
* @version 0.3.7
* @author lengyingxin <lengyingxin8966@gmail.com> (https://github.com/LengYXin)
*/
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var _isEqual = require('lodash/isEqual');
var _assign = require('lodash/assign');
var _map = require('lodash/map');
var _compact = require('lodash/compact');
var _head = require('lodash/head');
var _pick = require('lodash/pick');
var _merge = require('lodash/merge');
var _concat = require('lodash/concat');
var _eq = require('lodash/eq');
var tslib = require('tslib');
var dayjs = require('dayjs');
var jsCookie = require('js-cookie');
var jwtDecode = require('jwt-decode');
var lodashDecorators = require('lodash-decorators');
var mobx = require('mobx');
var mobxPersist = require('mobx-persist');
var rxjs = require('rxjs');
var _toLower = require('lodash/toLower');
var _includes = require('lodash/includes');
var _some = require('lodash/some');
var _isObject = require('lodash/isObject');
var _filter = require('lodash/filter');
var debug = require('debug');
var localforage = require('localforage');
var _delay = require('lodash/delay');
var _join = require('lodash/join');
var CryptoAes = require('crypto-js/aes');
var CryptoBase64 = require('crypto-js/enc-base64');
var CryptoHex = require('crypto-js/enc-hex');
var CryptoUtf8 = require('crypto-js/enc-utf8');
var CryptoCfb = require('crypto-js/mode-cfb');
var CryptoPkcs7 = require('crypto-js/pad-pkcs7');
var _isEmpty = require('lodash/isEmpty');
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
var _isEqual__default = /*#__PURE__*/_interopDefaultLegacy(_isEqual);
var _assign__default = /*#__PURE__*/_interopDefaultLegacy(_assign);
var _map__default = /*#__PURE__*/_interopDefaultLegacy(_map);
var _compact__default = /*#__PURE__*/_interopDefaultLegacy(_compact);
var _head__default = /*#__PURE__*/_interopDefaultLegacy(_head);
var _pick__default = /*#__PURE__*/_interopDefaultLegacy(_pick);
var _merge__default = /*#__PURE__*/_interopDefaultLegacy(_merge);
var _concat__default = /*#__PURE__*/_interopDefaultLegacy(_concat);
var _eq__default = /*#__PURE__*/_interopDefaultLegacy(_eq);
var dayjs__default = /*#__PURE__*/_interopDefaultLegacy(dayjs);
var jsCookie__default = /*#__PURE__*/_interopDefaultLegacy(jsCookie);
var jwtDecode__default = /*#__PURE__*/_interopDefaultLegacy(jwtDecode);
var _toLower__default = /*#__PURE__*/_interopDefaultLegacy(_toLower);
var _includes__default = /*#__PURE__*/_interopDefaultLegacy(_includes);
var _some__default = /*#__PURE__*/_interopDefaultLegacy(_some);
var _isObject__default = /*#__PURE__*/_interopDefaultLegacy(_isObject);
var _filter__default = /*#__PURE__*/_interopDefaultLegacy(_filter);
var debug__default = /*#__PURE__*/_interopDefaultLegacy(debug);
var localforage__default = /*#__PURE__*/_interopDefaultLegacy(localforage);
var _delay__default = /*#__PURE__*/_interopDefaultLegacy(_delay);
var _join__default = /*#__PURE__*/_interopDefaultLegacy(_join);
var CryptoAes__default = /*#__PURE__*/_interopDefaultLegacy(CryptoAes);
var CryptoBase64__default = /*#__PURE__*/_interopDefaultLegacy(CryptoBase64);
var CryptoHex__default = /*#__PURE__*/_interopDefaultLegacy(CryptoHex);
var CryptoUtf8__default = /*#__PURE__*/_interopDefaultLegacy(CryptoUtf8);
var CryptoCfb__default = /*#__PURE__*/_interopDefaultLegacy(CryptoCfb);
var CryptoPkcs7__default = /*#__PURE__*/_interopDefaultLegacy(CryptoPkcs7);
var _isEmpty__default = /*#__PURE__*/_interopDefaultLegacy(_isEmpty);
/**
* @description 认证模块
* @version 0.3.7
* @author lengyingxin <lengyingxin8966@gmail.com> (https://github.com/LengYXin)
*/
var AuthOptions =
/** @class */
function () {
function AuthOptions() {}
/**
* 日志输出
* @param namespace
* @param args
*/
AuthOptions.log = function (namespace) {
var args = [];
for (var _i = 1; _i < arguments.length; _i++) {
args[_i - 1] = arguments[_i];
}
if (!AuthOptions.browser && process.env.NODE_ENV === 'production') {
args = _filter__default["default"](args, function (x) {
return !_isObject__default["default"](x);
});
}
var log = debug__default["default"]("\u3010 Auth \u3011- " + namespace + " -");
log.enabled = true;
var formatter = args[0],
ars = args.slice(1);
log.apply(void 0, tslib.__spreadArray([formatter], ars));
log.destroy();
};
/**
* 日志输出带堆栈记录
* @static
* @param {string} namespace
* @param {*} args
* @memberof AuthOptions
*/
AuthOptions.trace = function (namespace) {
var args = [];
for (var _i = 1; _i < arguments.length; _i++) {
args[_i - 1] = arguments[_i];
}
AuthOptions.log.apply(AuthOptions, tslib.__spreadArray([namespace], args));
if (AuthOptions.browser) {
console === null || console === void 0 ? void 0 : console.groupCollapsed("%c -- [\u5806\u6808\u8BB0\u5F55] --", "color:#f5222d");
console === null || console === void 0 ? void 0 : console.trace(); // hidden in collapsed group
console === null || console === void 0 ? void 0 : console.groupEnd();
}
};
Object.defineProperty(AuthOptions, "isWeappBowser", {
/**
* 微信 小程序 浏览器
* @readonly
* @memberof XTGlobal
*/
get: function get() {
if (AuthOptions.browser) {
return _some__default["default"](['MiniProgramEnv', 'miniProgram'], function (agent) {
return _includes__default["default"](_toLower__default["default"](window.navigator.userAgent), _toLower__default["default"](agent));
});
}
},
enumerable: false,
configurable: true
});
Object.defineProperty(AuthOptions, "browser", {
/**
* 是否浏览器环境
* @readonly
* @memberof AppConfig
*/
get: function get() {
return typeof window !== 'undefined';
},
enumerable: false,
configurable: true
});
Object.defineProperty(AuthOptions, "micro", {
/**
* 微前端环境
* @readonly
* @static
* @memberof AuthOptions
*/
get: function get() {
if (AuthOptions.browser) {
return window.__MICRO_APP_ENVIRONMENT__ || false;
}
},
enumerable: false,
configurable: true
});
Object.defineProperty(AuthOptions, "LocalForage", {
/**
* localforage 访问器
* @readonly
* @private
* @static
* @memberof AuthOptions
*/
get: function get() {
if (AuthOptions._LocalForage) {
return AuthOptions._LocalForage;
}
var LocalForage = localforage__default["default"].createInstance({
// driver: localforage.LOCALSTORAGE, // Forc
name: AuthOptions.LocalforageKey // storeName: AuthOptions.StorageKey,
});
AuthOptions._LocalForage = LocalForage;
return LocalForage;
},
enumerable: false,
configurable: true
});
/**
* 创建 storage
* @static
* @return {*}
* @memberof AuthOptions
*/
AuthOptions.createStorage = function () {
if (!AuthOptions.browser) {
return {
clear: function clear() {
AuthOptions.log('clear');
},
setItem: function setItem(key, value) {
AuthOptions.log('setItem', key, value);
},
removeItem: function removeItem(key) {
AuthOptions.log('removeItem', key);
},
getItem: function getItem(key) {
AuthOptions.log('getItem', key);
}
};
}
var LocalForage = AuthOptions.LocalForage;
return {
clear: LocalForage.clear,
setItem: LocalForage.setItem,
removeItem: LocalForage.removeItem,
getItem: LocalForage.getItem
};
};
/**
* 持久化 mobx-persist
* @static
* @memberof basesOptions
*/
AuthOptions.createHydrate = function () {
var createStorage = AuthOptions.createStorage,
jsonify = AuthOptions.jsonify;
return mobxPersist.create({
jsonify: jsonify,
storage: createStorage()
});
};
/**
* 写入校验
* @static
* @memberof AuthOptions
*/
AuthOptions.writeCheck = function () {
if (AuthOptions.micro) {
AuthOptions.log('微应用禁止写入');
throw '微应用禁止写入';
}
};
/** 持久化序列化 */
AuthOptions.jsonify = true;
AuthOptions.LocalforageKey = 'mamba-portal-auth';
AuthOptions._LocalForage = undefined;
return AuthOptions;
}();
/**
* @description 认证模块
* @version 0.3.7
* @author lengyingxin <lengyingxin8966@gmail.com> (https://github.com/LengYXin)
*/
var AuthController =
/** @class */
function () {
function AuthController(options) {
if (options === void 0) {
options = {};
}
/**
* 持久化初始化完成 Subject
* @type {Promise<any>}
* @memberof ControllerUser
*/
this.HydrateSubject = new rxjs.Subject();
this.options = {
StorageKey: 'mamba-auth',
CookieKey: ['mamba-auth'],
CookieDomain: ['.lenovo.com.cn', '.lenovo.com'],
TokenType: 'JWT'
};
/**
* AccessToken
* @protected
* @memberof AuthController
*/
this._AccessToken = undefined;
/**
* 最后一次更新 值 HydrateisStopped 未完成前 存储 用于对比变化 default 表示默认无值
* @protected
* @memberof AuthController
*/
this.lastValue = 'default';
this.resetConfig(options);
this.createHydrate();
}
Object.defineProperty(AuthController.prototype, "HydrateAsync", {
/**
* 持久化初始化完成 Promise
* @type {Promise<any>}
* @memberof ControllerUser
*/
get: function get() {
return rxjs.lastValueFrom(this.HydrateSubject, {
defaultValue: undefined
});
},
enumerable: false,
configurable: true
});
Object.defineProperty(AuthController.prototype, "HydrateisStopped", {
/**
* 异步 HydrateSubject 已经完成
* @readonly
* @memberof PortalAuthController
*/
get: function get() {
return this.HydrateSubject.isStopped;
},
enumerable: false,
configurable: true
});
Object.defineProperty(AuthController.prototype, "JsCookie", {
get: function get() {
return jsCookie__default["default"];
},
enumerable: false,
configurable: true
});
Object.defineProperty(AuthController.prototype, "JWTDecode", {
get: function get() {
return jwtDecode__default["default"];
},
enumerable: false,
configurable: true
});
Object.defineProperty(AuthController.prototype, "IsJWT", {
get: function get() {
return _eq__default["default"](this.options.TokenType, 'JWT');
},
enumerable: false,
configurable: true
});
Object.defineProperty(AuthController.prototype, "StorageKey", {
/**
* 存储 key
* @readonly
* @memberof AuthController
*/
get: function get() {
return "_Auth_" + this.options.StorageKey;
},
enumerable: false,
configurable: true
});
Object.defineProperty(AuthController.prototype, "CookieKey", {
/**
* CookieKey
* @readonly
* @memberof AuthController
*/
get: function get() {
if (AuthOptions.browser) {
return _concat__default["default"]([], this.options.CookieKey);
}
return [];
},
enumerable: false,
configurable: true
});
Object.defineProperty(AuthController.prototype, "CookieDomain", {
/**
* Cookie 站点信息
* @readonly
* @memberof AuthController
*/
get: function get() {
if (AuthOptions.browser) {
return _concat__default["default"](["." + window.location.hostname], this.options.CookieDomain);
}
return [];
},
enumerable: false,
configurable: true
});
Object.defineProperty(AuthController.prototype, "AllCookieKeys", {
/**
* 所有的 Cookie
* @readonly
* @memberof AuthController
*/
get: function get() {
if (AuthOptions.browser) {
try {
var aKeys = document.cookie.replace(/((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:\1|$)/g, "").split(/\s*(?:\=[^;]*)?;\s*/);
for (var nIdx = 0; nIdx < aKeys.length; nIdx++) {
aKeys[nIdx] = decodeURIComponent(aKeys[nIdx]);
}
return aKeys;
} catch (error) {
return [];
}
}
},
enumerable: false,
configurable: true
});
/**
* 重置配置
* @param options
*/
AuthController.prototype.resetConfig = function (options) {
if (options === void 0) {
options = {};
}
try {
AuthOptions.writeCheck();
_merge__default["default"](this.options, _pick__default["default"](options, ['StorageKey', 'CookieKey', 'CookieDomain']));
} catch (error) {
AuthOptions.log('error', error);
}
};
Object.defineProperty(AuthController.prototype, "AccessToken", {
/**
* 提供外部访问的 AccessToken
* @readonly
* @memberof AuthController
*/
get: function get() {
var AccessToken = this.getAccessToken();
var Decoded = this.getDecoded(AccessToken);
if (Decoded && Decoded.overdue) {
AuthOptions.log('Warning 已过期 不返回', Decoded, this);
return undefined;
}
return AccessToken;
},
enumerable: false,
configurable: true
});
Object.defineProperty(AuthController.prototype, "JwtDecoded", {
/**
* 解析后的 JWT
* @readonly
* @type {JWTDecoded}
* @memberof AuthController
*/
get: function get() {
return this.getDecoded();
},
enumerable: false,
configurable: true
});
Object.defineProperty(AuthController.prototype, "CookieAccessToken", {
/**
* Cookie 中存储的值
* @readonly
* @private
* @memberof AuthController
*/
get: function get() {
// 微信小程序中不使用 cookie
if (AuthOptions.isWeappBowser) {
return undefined;
}
if (AuthOptions.browser) {
try {
return _head__default["default"](_compact__default["default"](_map__default["default"](this.CookieKey, function (key) {
return jsCookie__default["default"].get(key);
})));
} catch (error) {
AuthOptions.log('error', this, error);
return undefined;
}
}
},
enumerable: false,
configurable: true
});
/**
* 获取 JWT 解析后数据
* @returns
*/
AuthController.prototype.getDecoded = function (AccessToken) {
if (AccessToken === void 0) {
AccessToken = this.getAccessToken();
}
try {
if (!AccessToken || !this.IsJWT) {
return {};
}
var Decode = jwtDecode__default["default"](AccessToken);
return _assign__default["default"](Decode, {
expFormat: dayjs__default["default"](Decode.exp * 1000).format('YYYY-MM-DD HH:mm:ss'),
iatFormat: dayjs__default["default"](Decode.iat * 1000).format('YYYY-MM-DD HH:mm:ss'),
// 是否过期
overdue: dayjs__default["default"](Decode.exp * 1000).isBefore(dayjs__default["default"]())
});
} catch (error) {
// AuthOptions.log('error', 'Decoded', this, error)
return {
overdue: true
};
}
};
/**
* 获取 AccessToken
* @returns
*/
AuthController.prototype.getAccessToken = function () {
return _head__default["default"](_compact__default["default"]([this.CookieAccessToken, this._AccessToken]));
};
/**
* 保存 Token
* @param _AccessToken
* @returns
*/
AuthController.prototype.onSaveAccessToken = function (_AccessToken, setCookie) {
var _this = this;
if (_AccessToken === void 0) {
_AccessToken = undefined;
}
if (setCookie === void 0) {
setCookie = false;
}
try {
AuthOptions.writeCheck();
AuthOptions.trace('Save AccessToken', _AccessToken, setCookie);
if (_AccessToken && this.IsJWT) {
var Decoded = this.getDecoded(_AccessToken);
AuthOptions.log('AccessToken Decoded', Decoded); // if (!Decoded.aud) {
// throw 'AccessToken 非法'
// }
if (Decoded.overdue) {
throw 'AccessToken 已过期';
}
}
if (_AccessToken && _eq__default["default"](this.getAccessToken(), _AccessToken)) {
throw 'AccessToken 已存在 【 Cookie 存在将不在写入 】';
}
if (!this.HydrateisStopped) {
this.lastValue = _AccessToken;
}
this._AccessToken = _AccessToken;
if (setCookie && AuthOptions.browser) {
_map__default["default"](this.CookieDomain, function (domain) {
_map__default["default"](_this.CookieKey, function (key) {
AuthOptions.log('jsCookie set', key, _AccessToken, domain);
jsCookie__default["default"].set(key, _AccessToken);
jsCookie__default["default"].set(key, _AccessToken, {
domain: domain
});
});
});
}
} catch (error) {
AuthOptions.log('AccessToken Error', error, this);
}
};
/**
* 清理所有的登录信息
* @return {*}
* @memberof AuthController
*/
AuthController.prototype.onClear = function () {
var _this = this;
try {
AuthOptions.writeCheck();
this._AccessToken = undefined;
if (!this.HydrateisStopped) {
this.lastValue = undefined;
}
this.onRemove();
_map__default["default"](this.CookieDomain, function (domain) {
return _this.onRemove({
domain: domain
});
}); // return AuthOptions.LocalForage.clear();
} catch (error) {
AuthOptions.log('error', error);
}
};
AuthController.prototype.onRemove = function (options) {
if (AuthOptions.browser) {
try {
AuthOptions.writeCheck();
_map__default["default"](this.CookieKey, function (key) {
return jsCookie__default["default"].remove(key, options);
});
_map__default["default"](this.AllCookieKeys, function (key) {
return jsCookie__default["default"].remove(key, options);
});
} catch (error) {
AuthOptions.log('error', error);
}
}
};
/**
* 创建持久化存储
* @memberof BaseModel
*/
AuthController.prototype.createHydrate = function () {
return tslib.__awaiter(this, void 0, void 0, function () {
var Hydrate, Decoded, error_1;
var _this = this;
return tslib.__generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 2,, 3]);
if (!AuthOptions.browser) {
throw '非浏览器环境 不进行 Hydrate';
} // 微信小程序中不使用 cookie
if (AuthOptions.isWeappBowser) {
this.onRemove();
_map__default["default"](this.CookieDomain, function (domain) {
return _this.onRemove({
domain: domain
});
});
}
Hydrate = AuthOptions.createHydrate();
mobxPersist.persist({
_AccessToken: true
})(this);
AuthOptions.log("Storage " + this.StorageKey, this);
return [4
/*yield*/
, Hydrate(this.StorageKey, this)];
case 1:
_a.sent();
if (!_eq__default["default"](this.lastValue, 'default') && !_isEqual__default["default"](this._AccessToken, this.lastValue)) {
AuthOptions.log("Storage " + this.StorageKey + " LastValue", this, this.lastValue);
this.onSaveAccessToken(this.lastValue);
} // jwt 校验正确性
if (this.IsJWT) {
Decoded = this.getDecoded(); // 过期清理 或者无效
if (Decoded.overdue) {
this.onClear();
}
} // const CookieAccessToken = lodash.find(this.CookieAccessToken, lodash.identity);
// if (!this._AccessToken && CookieAccessToken) {
// this.onSaveAccessToken(CookieAccessToken)
// }
this.HydrateSubject.next(true);
this.HydrateSubject.complete();
return [3
/*break*/
, 3];
case 2:
error_1 = _a.sent();
if (AuthOptions.browser) {
AuthOptions.log('error', error_1);
}
this.HydrateSubject.next(false);
this.HydrateSubject.complete();
return [3
/*break*/
, 3];
case 3:
return [2
/*return*/
];
}
});
});
};
tslib.__decorate([mobx.observable], AuthController.prototype, "_AccessToken", void 0);
tslib.__decorate([mobx.computed], AuthController.prototype, "AccessToken", null);
tslib.__decorate([mobx.computed], AuthController.prototype, "JwtDecoded", null);
tslib.__decorate([mobx.action], AuthController.prototype, "onSaveAccessToken", null);
tslib.__decorate([mobx.action], AuthController.prototype, "onClear", null);
AuthController = tslib.__decorate([lodashDecorators.BindAll()], AuthController);
return AuthController;
}();
/**
* @description 认证模块
* @version 0.3.7
* @author lengyingxin <lengyingxin8966@gmail.com> (https://github.com/LengYXin)
*/
var day = dayjs__default["default"]().format('YYYY-MM-DD');
var AuthEncryption =
/** @class */
function () {
function AuthEncryption() {}
/**
* 加密
* @static
* @param {string} message
* @return {*}
* @memberof Encryption
*/
AuthEncryption.AES_Encrypt = function (message) {
try {
var srcs = CryptoUtf8__default["default"].parse(message);
var encrypted = CryptoAes__default["default"].encrypt(srcs, AuthEncryption.AES_Config.AES_Key, {
iv: AuthEncryption.AES_Config.AES_IV,
mode: CryptoCfb__default["default"],
padding: CryptoPkcs7__default["default"]
});
return encrypted.ciphertext.toString().toUpperCase();
} catch (error) {
console.error('LENG ~ Encryption ~ AES_Encrypt ~ error', error);
return '';
}
};
/**
* 解密
* @static
* @param {string} message
* @return {*}
* @memberof Encryption
*/
AuthEncryption.AES_Decrypt = function (message) {
try {
var encryptedHexStr = CryptoHex__default["default"].parse(message);
var srcs = CryptoBase64__default["default"].stringify(encryptedHexStr);
var decrypt = CryptoAes__default["default"].decrypt(srcs, AuthEncryption.AES_Config.AES_Key, {
iv: AuthEncryption.AES_Config.AES_IV,
mode: CryptoCfb__default["default"],
padding: CryptoPkcs7__default["default"]
});
var decryptedStr = decrypt.toString(CryptoUtf8__default["default"]);
return decryptedStr.toString();
} catch (error) {
console.error('LENG ~ Encryption ~ AES_Decrypt ~ error', error);
return '';
}
};
/** @type AES_Key 秘钥 当前日期 */
AuthEncryption.AES_Config = {
AES_Key: CryptoUtf8__default["default"].parse('day'),
AES_IV: CryptoHex__default["default"].parse('day'),
set: function set(SystemInfo) {
var keys = []; // 小程序的 webview 中
if (_some__default["default"](['MiniProgramEnv', 'miniProgram'], function (agent) {
return _includes__default["default"](_toLower__default["default"](SystemInfo.userAgent), _toLower__default["default"](agent));
})) {
// const system = lodash.join(
// [SystemInfo.os.name, SystemInfo.os.version],
// ' ',
// );
// const version = lodash.join(
// lodash.take(lodash.split(SystemInfo.browser.version, '.'), 3),
// '.',
// );
keys = [day]; //lodash.concat(keys, [version]);
} else if (SystemInfo.system) {
// 小程序中
keys = [day]; //lodash.concat(keys, [SystemInfo.version]);
}
var keyStr = _join__default["default"](keys, ' ');
AuthEncryption.AES_Config.AES_Key = CryptoUtf8__default["default"].parse(keyStr);
AuthEncryption.AES_Config.AES_IV = CryptoHex__default["default"].parse(keyStr);
_delay__default["default"](function () {
return console.log('Encryption', SystemInfo, keyStr);
}, 1000);
}
};
return AuthEncryption;
}();
/**
* @description 认证模块
* @version 0.3.7
* @author lengyingxin <lengyingxin8966@gmail.com> (https://github.com/LengYXin)
*/
var env = {
version: "0.3.7",
timestamp: "2023-01-06 12:05"
};
/**
* @description 认证模块
* @version 0.3.7
* @author lengyingxin <lengyingxin8966@gmail.com> (https://github.com/LengYXin)
*/
var InfoController =
/** @class */
function () {
function InfoController(options) {
if (options === void 0) {
options = {
StorageKey: 'mamba-auth-info'
};
}
this.options = options;
/**
* 持久化初始化完成 Subject
* @type {Promise<any>}
* @memberof ControllerUser
*/
this.HydrateSubject = new rxjs.Subject();
/**
* 数据存储对象
* @protected
* @type {T}
* @memberof InfoController
*/
this._value = undefined;
/**
* 最后一次更新 值 HydrateisStopped 未完成前 存储 用于对比变化
* @protected
* @memberof AuthController
*/
this.lastValue = undefined;
this.createHydrate();
}
Object.defineProperty(InfoController.prototype, "HydrateAsync", {
/**
* 持久化初始化完成 Promise
* @type {Promise<any>}
* @memberof ControllerUser
*/
get: function get() {
return rxjs.lastValueFrom(this.HydrateSubject, {
defaultValue: undefined
});
},
enumerable: false,
configurable: true
});
Object.defineProperty(InfoController.prototype, "HydrateisStopped", {
/**
* 异步 HydrateSubject 已经完成
* @readonly
* @memberof PortalAuthController
*/
get: function get() {
return this.HydrateSubject.isStopped;
},
enumerable: false,
configurable: true
});
Object.defineProperty(InfoController.prototype, "StorageKey", {
get: function get() {
return "_Auth_" + this.options.StorageKey;
},
enumerable: false,
configurable: true
});
Object.defineProperty(InfoController.prototype, "value", {
/**
* 外部可访问对象
* @readonly
* @type {T}
* @memberof InfoController
*/
get: function get() {
return this._value;
},
enumerable: false,
configurable: true
});
/**
* 保存 Token
* @param _AccessToken
* @returns
*/
InfoController.prototype.onSave = function (value) {
try {
AuthOptions.writeCheck();
if (_isEqual__default["default"](value, this._value)) {
return AuthOptions.log('Save Value 无值改变', value, '=>', this._value);
}
if (mobx.isObservable(value)) {
value = mobx.toJS(value);
}
if (!this.HydrateisStopped) {
this.lastValue = value;
}
this._value = value;
} catch (error) {
AuthOptions.log('error', error);
}
};
/**
* 清理所有的登录信息
* @return {*}
* @memberof AuthController
*/
InfoController.prototype.onClear = function () {
this.onSave(undefined);
};
/**
* 创建持久化存储
* @memberof BaseModel
*/
InfoController.prototype.createHydrate = function () {
return tslib.__awaiter(this, void 0, void 0, function () {
var Hydrate, error_1;
return tslib.__generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 2,, 3]);
if (!AuthOptions.browser) {
throw '非浏览器环境 不进行 Hydrate';
}
Hydrate = AuthOptions.createHydrate();
mobxPersist.persist({
_value: {
type: 'object'
}
})(this);
AuthOptions.log("Info " + this.StorageKey, this);
return [4
/*yield*/
, Hydrate(this.StorageKey, this)];
case 1:
_a.sent();
if (!_isEmpty__default["default"](this.lastValue) && !_isEqual__default["default"](this._value, this.lastValue)) {
AuthOptions.log("Info " + this.StorageKey + " LastValue", this, this.lastValue);
this.onSave(this.lastValue);
}
this.HydrateSubject.next(true);
this.HydrateSubject.complete();
return [3
/*break*/
, 3];
case 2:
error_1 = _a.sent();
if (AuthOptions.browser) {
AuthOptions.log('error', error_1);
}
this.HydrateSubject.next(false);
this.HydrateSubject.complete();
return [3
/*break*/
, 3];
case 3:
return [2
/*return*/
];
}
});
});
};
tslib.__decorate([mobx.observable], InfoController.prototype, "_value", void 0);
tslib.__decorate([mobx.computed], InfoController.prototype, "value", null);
tslib.__decorate([mobx.action], InfoController.prototype, "onSave", null);
InfoController = tslib.__decorate([lodashDecorators.BindAll()], InfoController);
return InfoController;
}();
/**
* @description 认证模块
* @version 0.3.7
* @author lengyingxin <lengyingxin8966@gmail.com> (https://github.com/LengYXin)
*/
/**
* Portal 认证信息 BP&SP
* @export
* @class PortalAuthController
*/
var PortalAuthController =
/** @class */
function () {
function PortalAuthController(options) {
if (options === void 0) {
options = {
PortalType: 'BP'
};
}
var _a;
this.options = options;
/**
* 持久化初始化完成 Subject
* @type {Promise<any>}
* @memberof ControllerUser
*/
this.HydrateSubject = new rxjs.Subject(); // 浏览器
if (AuthOptions.browser) {
// 微前端 环境中
if (AuthOptions.micro && ((_a = window === null || window === void 0 ? void 0 : window.rawWindow) === null || _a === void 0 ? void 0 : _a.PortalAuth)) {
PortalAuthController_1.PortalAuth = window.rawWindow.PortalAuth;
} else if (window === null || window === void 0 ? void 0 : window.PortalAuth) {
PortalAuthController_1.PortalAuth = window.PortalAuth;
} // 非微前端环境
if (!AuthOptions.micro) {
window.PortalAuth = this;
} // 单例
if (PortalAuthController_1.PortalAuth) {
return PortalAuthController_1.PortalAuth;
}
}
PortalAuthController_1.createAuth(this.options);
PortalAuthController_1.PortalInfo = new InfoController({
StorageKey: 'PortalInfo'
});
PortalAuthController_1.PortalDrainage = new InfoController({
StorageKey: 'PortalDrainage'
});
this.createHydrate();
PortalAuthController_1.PortalAuth = this;
AuthOptions.log('PortalAuth', this);
}
PortalAuthController_1 = PortalAuthController;
Object.defineProperty(PortalAuthController, "env", {
get: function get() {
return env;
},
enumerable: false,
configurable: true
});
Object.defineProperty(PortalAuthController.prototype, "env", {
get: function get() {
return env;
},
enumerable: false,
configurable: true
});
PortalAuthController.createAuth = function (options) {
switch (options.PortalType) {
case 'BP':
PortalAuthController_1.BPAuth = new AuthController({
CookieKey: ['BPPORTAL_TOKEN'],
StorageKey: 'BPPortal',
TokenType: options.TokenType || 'JWT'
});
return;
case 'SP':
PortalAuthController_1.SPAuth = new AuthController({
CookieKey: ['SALES_TOKEN'],
StorageKey: 'SALESPortal',
TokenType: options.TokenType || 'Other'
});
return;
default:
PortalAuthController_1.GeneralAuth = new AuthController({
CookieKey: ['BPPORTAL_TOKEN', 'SALES_TOKEN'],
StorageKey: 'Portal',
TokenType: options.TokenType || 'Other'
});
}
};
Object.defineProperty(PortalAuthController.prototype, "HydrateAsync", {
/**
* 持久化初始化完成 Promise
* @type {Promise<any>}
* @memberof ControllerUser
*/
get: function get() {
return rxjs.lastValueFrom(this.HydrateSubject, {
defaultValue: undefined
});
},
enumerable: false,
configurable: true
});
Object.defineProperty(PortalAuthController.prototype, "HydrateisStopped", {
/**
* 异步 HydrateSubject 已经完成
* @readonly
* @memberof PortalAuthController
*/
get: function get() {
return this.HydrateSubject.isStopped;
},
enumerable: false,
configurable: true
});
Object.defineProperty(PortalAuthController.prototype, "BPAuth", {
/**
* BP Auth
* @type {AuthController}
* @memberof PortalAuthController
*/
get: function get() {
return PortalAuthController_1.BPAuth;
},
enumerable: false,
configurable: true
});
Object.defineProperty(PortalAuthController.prototype, "SPAuth", {
/**
* SP Auth
* @type {AuthController}
* @memberof PortalAuthController
*/
get: function get() {
return PortalAuthController_1.SPAuth;
},
enumerable: false,
configurable: true
});
Object.defineProperty(PortalAuthController.prototype, "GeneralAuth", {
/**
* 通用的 Auth
* @type {AuthController}
* @memberof PortalAuthController
*/
get: function get() {
return PortalAuthController_1.GeneralAuth;
},
enumerable: false,
configurable: true
});
Object.defineProperty(PortalAuthController.prototype, "PortalInfo", {
/**
* 数据 Info
* @readonly
* @memberof PortalAuthController
*/
get: function get() {
return PortalAuthController_1.PortalInfo;
},
enumerable: false,
configurable: true
});
Object.defineProperty(PortalAuthController.prototype, "PortalDrainage", {
/**
* 数据 引流
* @readonly
* @protected
* @memberof PortalAuthController
*/
get: function get() {
return PortalAuthController_1.PortalDrainage;
},
enumerable: false,
configurable: true
});
Object.defineProperty(PortalAuthController.prototype, "Info", {
/**
* 基础数据
* @readonly
* @memberof PortalAuthController
*/
get: function get() {
return mobx.toJS(this.PortalInfo.value);
},
enumerable: false,
configurable: true
});
Object.defineProperty(PortalAuthController.prototype, "Drainage", {
/**
* 引流数据
* @readonly
* @memberof PortalAuthController
*/
get: function get() {
return mobx.toJS(this.PortalDrainage.value);
},
enumerable: false,
configurable: true
});
Object.defineProperty(PortalAuthController.prototype, "AccessToken", {
/**
* AccessToken 返回校验 时间是否过期 过期 的 AccessToken 不返回
* @readonly
* @memberof PortalAuthController
*/
get: function get() {
switch (this.options.PortalType) {
case 'BP':
return this.BPAuth.AccessToken;
case 'SP':
return this.SPAuth.AccessToken;
default:
return this.GeneralAuth.AccessToken;
}
},
enumerable: false,
configurable: true
});
Object.defineProperty(PortalAuthController.prototype, "JwtDecoded", {
/**
* AccessToken 解码信息
* @readonly
* @memberof PortalAuthController
*/
get: function get() {
switch (this.options.PortalType) {
case 'BP':
return this.BPAuth.JwtDecoded;
case 'SP':
return this.SPAuth.JwtDecoded;
default:
return this.GeneralAuth.JwtDecoded;
}
},
enumerable: false,
configurable: true
});
/**
* 保存 AccessToken 校验有效性 无效过滤
* @param {string} [AccessToken=undefined]
* @memberof PortalAuthController
*/
PortalAuthController.prototype.onSaveAccessToken = function (AccessToken, setCookie) {
var _a, _b, _c;
if (AccessToken === void 0) {
AccessToken = undefined;
}
if (setCookie === void 0) {
setCookie = false;
}
(_a = this.BPAuth) === null || _a === void 0 ? void 0 : _a.onSaveAccessToken(AccessToken, setCookie);
(_b = this.SPAuth) === null || _b === void 0 ? void 0 : _b.onSaveAccessToken(AccessToken, setCookie);
(_c = this.GeneralAuth) === null || _c === void 0 ? void 0 : _c.onSaveAccessToken(AccessToken, setCookie);
};
/**
* 存储info 信息
* @param {*} value
* @memberof PortalAuthController
*/
PortalAuthController.prototype.onSaveInfo = function (value) {
this.PortalInfo.onSave(value);
AuthOptions.trace('Save Info', value);
};
/**
* 存储 Drainage 信息
* @param {*} value
* @memberof PortalAuthController
*/
PortalAuthController.prototype.onSaveDrainage = function (value) {
this.PortalDrainage.onSave(value);
AuthOptions.trace('Save Drainage', value);
};
/**
* 清理所有的登录信息
* @return {*}
* @memberof AuthController
*/
PortalAuthController.prototype.onClear = function () {
var _a, _b, _c, _d, _e, _f, _g;
return tslib.__awaiter(this, void 0, void 0, function () {
var error_1;
return tslib.__generator(this, function (_h) {
switch (_h.label) {
case 0:
_h.trys.push([0, 4,, 5]);
AuthOptions.writeCheck();
AuthOptions.trace('clear start');
(_a = this.BPAuth) === null || _a === void 0 ? void 0 : _a.onClear();
(_b = this.SPAuth) === null || _b === void 0 ? void 0 : _b.onClear();
(_c = this.GeneralAuth) === null || _c === void 0 ? void 0 : _c.onClear();
(_d = this.PortalInfo) === null || _d === void 0 ? void 0 : _d.onClear();
(_e = this.PortalDrainage) === null || _e === void 0 ? void 0 : _e.onClear();
if (!AuthOptions.browser) return [3
/*break*/
, 3];
(_f = window.localStorage) === null || _f === void 0 ? void 0 : _f.clear();
(_g = window.sessionStorage) === null || _g === void 0 ? void 0 : _g.clear();
return [4
/*yield*/
, this.HydrateAsync];
case 1:
_h.sent();
return [4
/*yield*/
, AuthOptions.LocalForage.clear()];
case 2:
_h.sent();
_h.label = 3;
case 3:
AuthOptions.log('clear success', 'localStorage,sessionStorage,IndexedDB,cookie 全部清理');
return [3
/*break*/
, 5];
case 4:
error_1 = _h.sent();
AuthOptions.trace('clear error', error_1);
return [3
/*break*/
, 5];
case 5:
return [2
/*return*/
];
}
});
});
};
/**
* 创建持久化存储
* @memberof BaseModel
*/
PortalAuthController.prototype.createHydrate = function () {
var _a, _b, _c, _d;
return tslib.__awaiter(this, void 0, void 0, function () {
var observables, error_2;
return tslib.__generator(this, function (_e) {
switch (_e.label) {
case 0:
_e.trys.push([0, 2,, 3]);
observables = _compact__default["default"]([(_a = this.BPAuth) === null || _a === void 0 ? void 0 : _a.HydrateAsync, (_b = this.SPAuth) === null || _b === void 0 ? void 0 : _b.HydrateAsync, (_c = this.GeneralAuth) === null || _c === void 0 ? void 0 : _c.HydrateAsync, (_d = this.PortalInfo) === null || _d === void 0 ? void 0 : _d.HydrateAsync]);
return [4
/*yield*/
, rxjs.lastValueFrom(rxjs.zip(observables), {
defaultValue: undefined
})];
case 1:
_e.sent();
this.HydrateSubject.next(true);
this.HydrateSubject.complete();
return [3
/*break*/
, 3];
case 2:
error_2 = _e.sent();
AuthOptions.trace('error', error_2);
this.HydrateSubject.next(false);
this.HydrateSubject.complete();
return [3
/*break*/
, 3];
case 3:
return [2
/*return*/
];
}
});
});
};
var PortalAuthController_1;
/**
* 存储的单列
* @private
* @static
* @type {PortalAuthController}
* @memberof PortalAuthController
*/
PortalAuthController.PortalAuth = undefined;
/**
* 混合认证
* @protected
* @static
* @type {AuthController}
* @memberof PortalAuthController
*/
PortalAuthController.GeneralAuth = undefined;
/**
* BP 认证
* @protected
* @static
* @type {AuthController}
* @memberof PortalAuthController
*/
PortalAuthController.BPAuth = undefined;
/**
* SP 认证
* @protected
* @static
* @type {AuthController}
* @memberof PortalAuthController
*/
PortalAuthController.SPAuth = undefined;
/**
* 基础信息
* @protected
* @static
* @type {InfoController}
* @memberof PortalAuthController
*/
PortalAuthController.PortalInfo = undefined;
/**
* 引流信息
* @protected
* @static
* @type {InfoController}
* @memberof PortalAuthController
*/
PortalAuthController.PortalDrainage = undefined;
tslib.__decorate([mobx.computed], PortalAuthController.prototype, "Info", null);
tslib.__decorate([mobx.computed], PortalAuthController.prototype, "Drainage", null);
tslib.__decorate([mobx.computed], PortalAuthController.prototype, "AccessToken", null);
tslib.__decorate([mobx.computed], PortalAuthController.prototype, "JwtDecoded", null);
PortalAuthController = PortalAuthController_1 = tslib.__decorate([lodashDecorators.BindAll()], PortalAuthController);
return PortalAuthController;
}();
exports.AuthController = AuthController;
exports.AuthEncryption = AuthEncryption;
exports.AuthOptions = AuthOptions;
exports.PortalAuthController = PortalAuthController;
//# sourceMappingURL=index.bundles.js.map