| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373 |
- import Vue from 'vue';
- import { hexMD5 } from '../pages/login/md5.js';
- // 登录超时时间配置(毫秒)
- const LOGIN_TIMEOUT = 15000;
- const SSO_TIMEOUT = 10000;
- // 错误处理包装器
- function safeResolve(promise) {
- return promise.catch(err => {
- console.error('登录流程异常:', err);
- return false;
- });
- }
- // 带超时的 Promise
- function withTimeout(promise, timeoutMs = 10000, fallback = false) {
- return Promise.race([
- promise,
- new Promise(resolve => setTimeout(() => resolve(fallback), timeoutMs))
- ]).catch(() => fallback);
- }
- /* 获取用户权限 - 带超时和错误处理 */
- function query_userauth() {
- return withTimeout(
- new Promise((resolve) => {
- Vue.prototype.$Http.basic({
- "classname": "sysmanage.develop.userauth.userauth",
- "method": "query_userauth",
- content: {
- nocache: true
- }
- }).then(res => {
- console.log("查询用户权限", res)
- if (Vue.prototype.cutoff(res.msg)) {
- resolve(false);
- return;
- }
- parsingAuth(res.data);
- resolve(true);
- }).catch(() => resolve(false));
- }),
- SSO_TIMEOUT,
- false
- );
- }
- /* 查询站点数据 - 带超时和错误处理 */
- function querySite_Parameter() {
- return withTimeout(
- new Promise((resolve) => {
- Vue.prototype.$Http.basic({
- "classname": "webmanage.site.site",
- "method": "querySite_Parameter",
- "content": {}
- }).then(res => {
- console.log("查询站点配置", res)
- if (Vue.prototype.cutoff(res.msg)) {
- resolve(false);
- return;
- }
- try {
- uni.removeStorageSync('siteP');
- uni.setStorageSync('siteP', res.data);
- } catch (e) {
- console.error('缓存站点数据失败:', e);
- }
- resolve(true);
- }).catch(() => resolve(false));
- }),
- SSO_TIMEOUT,
- false
- );
- }
- /* 格式化权限 */
- function parsingAuth(list) {
- let authList = {}
- list.forEach(system => {
- // let systemObj = {}
- system.modules.forEach(app => {
- let appObj = {}
- app.apps.forEach(m => {
- appObj[m.meta.title] = {
- path: m.path,
- pathDetail: m.path_index,
- pathDetail: m.path_index,
- name: m.name,
- remark: m.meta.title,
- remarks: m.remarks,
- cover: m.cover,
- option: m.meta.auth.map(v => v.option),
- forms: m.meta.forms,
- optionname: m.meta.auth.map(v => v.optionname)
- }
- })
- // systemObj[app.systemmodulename] = appObj;
- authList[app.systemmodulename] = appObj;
- })
- // authList[system.systemname] = systemObj;
- });
- uni.removeStorageSync({
- key: 'authList'
- })
- uni.setStorageSync('authList', authList)
- }
- class Login {
- // 防止重复登录标志
- _isLoggingIn = false;
- /* 使用缓存的账号密码登录 - 带超时 */
- cachedAccountLogin() {
- return new Promise((resolve) => {
- // 防止重复调用
- if (this._isLoggingIn) {
- resolve(false);
- return;
- }
- this._isLoggingIn = true;
- const cachedAccount = uni.getStorageSync('accountno');
- const cachedPassword = uni.getStorageSync('accountnoPwd');
- if (!cachedAccount || !cachedPassword) {
- console.log("无缓存的账号密码");
- this._isLoggingIn = false;
- return resolve(false);
- }
- console.log("使用缓存的账号密码登录", cachedAccount);
- // 判断是否需要先走门店登录
- if (Vue.prototype.$Http.baseUrl === "https://meida.cnyunl.com:888") {
- withTimeout(
- this.tryStoreLogin(cachedAccount, cachedPassword),
- LOGIN_TIMEOUT
- ).then(result => {
- this._isLoggingIn = false;
- resolve(result);
- }).catch(() => {
- this._isLoggingIn = false;
- resolve(false);
- });
- } else {
- withTimeout(
- this.tryNewSystemLogin(cachedAccount, cachedPassword),
- LOGIN_TIMEOUT
- ).then(result => {
- this._isLoggingIn = false;
- resolve(result);
- }).catch(() => {
- this._isLoggingIn = false;
- resolve(false);
- });
- }
- });
- }
- /* 门店登录 -> SSO -> SSO2 */
- tryStoreLogin(account, password) {
- return new Promise((resolve) => {
- Vue.prototype.$Http.OldLogin(`?username=${account}&password=${encodeURIComponent(password)}`)
- .then(oldLoginResult => {
- console.log("门店登录结果:", oldLoginResult);
- if (oldLoginResult.success === true) {
- console.log("门店登录成功,开始单点登录到CRM");
- return Vue.prototype.$Http.SSO({
- accountno: oldLoginResult.data.userinfo.username,
- password: oldLoginResult.data.cookie.split("=")[1],
- systemclient: getApp().globalData.systemclient
- });
- } else {
- console.log("门店登录失败,尝试E订单登录");
- throw new Error('STORE_LOGIN_FAILED');
- }
- })
- .then(ssoResult => {
- console.log("SSO单点登录到CRM结果:", ssoResult);
- if (ssoResult.code === 1) {
- return this.handleSSO2(ssoResult);
- } else {
- console.log("SSO失败:", ssoResult.msg);
- resolve(false);
- }
- })
- .catch(err => {
- if (err.message === 'STORE_LOGIN_FAILED') {
- this.tryNewSystemLogin(account, password).then(resolve);
- } else {
- console.log("门店登录异常,尝试E订单登录:", err);
- this.tryNewSystemLogin(account, password).then(resolve);
- }
- });
- });
- }
- /* E订单登录 -> SSO2 */
- tryNewSystemLogin(account, passwordMD5) {
- return new Promise((resolve) => {
- console.log("尝试E订单登录", account);
- Vue.prototype.$Http.login({
- accountno: account,
- password: hexMD5(passwordMD5),
- systemclient: 'mdyxb'
- }).then(res => {
- if (res.code === 1) {
- console.log("缓存登录成功,开始SSO2", res);
- return this.handleSSO2(res);
- } else {
- console.log("缓存登录失败", res.msg);
- resolve(false);
- }
- }).catch(err => {
- console.log("缓存登录异常", err);
- resolve(false);
- });
- });
- }
- /* 处理 SSO2 结果 */
- handleSSO2(acc) {
- return new Promise((resolve) => {
- console.log("开始SSO2登录", acc);
- Vue.prototype.$Http.SSO2({
- accountno: acc.account_list[0].accountno,
- password: acc.account_list[0].token,
- accesstoken: acc.account_list[0].token,
- systemclient: acc.account_list[0].systemclient
- }).then(sso2Res => {
- if (sso2Res.code === 1) {
- console.log("SSO2成功", sso2Res);
- const account = { ...sso2Res.account_list.find(v => v.siteid == 'MD') || sso2Res.account_list[0] };
- try {
- uni.removeStorageSync('userMsg');
- uni.setStorageSync('userMsg', account);
- } catch (e) {
- console.error('存储用户信息失败:', e);
- }
-
- // 异步加载用户权限和站点参数
- const initPromise = Promise.all([query_userauth(), querySite_Parameter()]);
-
- getApp().globalData.systemInitIsComplete = initPromise;
-
- initPromise.then(() => {
- getApp().globalData.systemInitIsComplete = true;
- getApp().globalData.HomePageStartRendering.forEach(v => {
- try {
- v();
- } catch (e) {
- console.error('HomePageStartRendering 回调执行失败:', e);
- }
- });
- uni.reLaunch({
- url: '/pages/index/index',
- fail: () => {
- // 跳转失败时静默处理
- console.warn('reLaunch 跳转失败');
- }
- });
- }).catch(err => {
- console.error('初始化失败:', err);
- getApp().globalData.systemInitIsComplete = true;
- });
-
- resolve(true);
- } else {
- console.log("SSO2失败", sso2Res.msg);
- resolve(false);
- }
- }).catch(err => {
- console.log("SSO2异常", err);
- resolve(false);
- });
- });
- }
- /* 微信游客登录 - 带超时和错误处理 */
- wechatLogin() {
- return new Promise((resolve) => {
- if (this._isLoggingIn) {
- resolve(false);
- return;
- }
- this._isLoggingIn = true;
- uni.login({
- timeout: 10000,
- success(res) {
- Vue.prototype.$Http.loginbywechat({
- wechat_code: res.code,
- systemclient: getApp().globalData.systemclient
- }).then(res => {
- Vue.prototype.$Http.systemclient = getApp().globalData.systemclient;
- console.log("微信登录", res);
- if (Vue.prototype.cutoff(res.msg)) {
- this._isLoggingIn = false;
- return resolve(false);
- }
-
- try {
- uni.removeStorageSync('userMsg');
- uni.setStorageSync('userMsg', res.account_list[0]);
- } catch (e) {
- console.error('存储微信登录信息失败:', e);
- }
-
- // 异步初始化权限和配置
- const initPromise = Promise.all([query_userauth(), querySite_Parameter()]);
- getApp().globalData.systemInitIsComplete = initPromise;
-
- initPromise.then(() => {
- getApp().globalData.systemInitIsComplete = true;
- getApp().globalData.HomePageStartRendering.forEach(v => {
- try {
- v();
- } catch (e) {
- console.error('HomePageStartRendering 回调执行失败:', e);
- }
- });
- if (uni.getStorageSync('accountnoPwd')) {
- uni.navigateTo({
- url: "/pages/login/login",
- fail: () => console.warn('跳转到登录页失败')
- });
- }
- this._isLoggingIn = false;
- resolve(res.account_list[0].token);
- }).catch(() => {
- this._isLoggingIn = false;
- resolve(false);
- });
- }).catch(() => {
- this._isLoggingIn = false;
- resolve(false);
- });
- },
- fail: () => {
- console.log("微信登录失败");
- this._isLoggingIn = false;
- resolve(false);
- }
- });
- });
- }
- /* 自动登录入口 - 带超时保护 */
- autoLogin() {
- return new Promise((resolve) => {
- // 设置登录超时
- const timeout = setTimeout(() => {
- console.warn('登录流程超时');
- this._isLoggingIn = false;
- resolve(false);
- }, LOGIN_TIMEOUT + 5000);
- this.cachedAccountLogin().then(isCacheLoginSuccess => {
- clearTimeout(timeout);
- if (isCacheLoginSuccess) {
- console.log("缓存登录成功");
- resolve(true);
- } else {
- console.log("缓存登录失败,尝试微信登录");
- this.wechatLogin().then(result => {
- resolve(result);
- });
- }
- });
- });
- }
- }
- export {
- Login
- }
|