| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176 |
- import { wecomAuth } from "@/api/indexAI";
- import router from '@/router'; // 导入你的路由实例
- // 企业微信登录相关类型定义(无变化,无需可选链)
- export interface GuidInfo {
- guid: string;
- time: number; // 时间戳(毫秒)
- }
- export interface LastCode {
- code: string;
- }
- export interface WecomAuthResponse {
- StatusCode: number;
- Data: {
- token: string; // AIToken
- };
- Message?: string;
- }
- // 登录中状态锁(避免并发登录请求)
- let isLogging = false;
- /**
- * 校验是否已登录(AIToken 存在 + guidInfo 未过期)
- * @returns {boolean} 是否已登录
- */
- export const checkLoginStatus = (): boolean => {
- const AIToken = window.localStorage.getItem('AIToken');
- const guidInfoStr = window.localStorage.getItem('guidInfo');
- if (!AIToken) return false;
- if (!guidInfoStr) return false;
- return true;
- // try {
- // const guidInfo: GuidInfo = JSON.parse(guidInfoStr);
- // const currentTime = new Date().getTime();
- // const expireTime = 1000 * 60 * 60 * 12; // 12 小时过期
- // return guidInfo && guidInfo.guid && (currentTime - guidInfo.time) < expireTime;
- // } catch (error) {
- // return false;
- // }
- };
- /**
- * 初始化 guidInfo
- */
- export const initGuidInfo = (): void => {
- let guidInfo = JSON.parse(window.localStorage.getItem("guidInfo"));
- const currentTime = new Date().getTime();
- const guid = getGuid();
- const guidTime = new Date().getTime();
- const newGuidInfo: GuidInfo = { guid, time: guidTime };
- // 有缓存但过期-存储
- if (guidInfo && (currentTime - guidInfo.time) >= (1000 * 60 * 60 * 12)) {
- window.localStorage.setItem("guidInfo", JSON.stringify(newGuidInfo));
- window.localStorage.removeItem('lastCode');
- } else if (!guidInfo) {
- // 无缓存-存储
- window.localStorage.setItem('guidInfo', JSON.stringify(newGuidInfo));
- }
- };
- /**
- * 企业微信登录核心流程(获取 code → 兑换 AIToken)
- * @param code 企业微信授权返回的 code
- * @returns {Promise<void>}
- */
- export const doWecomLogin = async (code: string): Promise<void> => {
- if (isLogging) return; // 正在登录中,忽略重复调用
- isLogging = true;
- try {
- const lastCodeStr = window.localStorage.getItem('lastCode');
- const lastCode: LastCode | null = lastCodeStr ? JSON.parse(lastCodeStr) : null;
- // 同一 code 不重复请求
- if (lastCode && lastCode.code === code) {
- isLogging = false;
- return;
- }
- // 存储当前 code,避免重复使用
- window.localStorage.setItem('lastCode', JSON.stringify({ code }));
- const formData = new FormData();
- formData.append('code', code);
- // 本地登录-需注释
- // formData.append("code", 'QWert!@345');
- // 调用接口兑换 AIToken
- const res: WecomAuthResponse = await wecomAuth(formData);
- if (res && res.StatusCode === 200 && res.Data && res.Data.token) {
- // 登录成功:存储 AIToken
- window.localStorage.setItem('AIToken', res.Data.token);
- // 处理身份,身份可能为多个,只能按身份权限大小来固定为某个身份;
- let roleIds = res.Data.roleIds, agent = '';
- if (roleIds) {
- if (roleIds.includes('2')) {
- agent = 'stoneLikePaint';//服务商
- } else if (roleIds.includes('0')) {
- agent = 'ssb';//经销商
- } else if (roleIds.includes('4')) {
- agent = 'dg';//导购
- } else if (roleIds.includes('1')) {
- agent = 'hbs';//好邦手
- } else if (roleIds.includes('3')) {
- agent = 'goldShop';//金牌店
- }
- console.log("roleIds=", roleIds)
- console.log("agent=", agent)
- window.localStorage.setItem('agentFrom', agent);
- window.localStorage.setItem('agentFromAI', agent);
- }
- isLogging = false;
- // console.log("router.currentRoute.fullPath=",router.currentRoute.fullPath)
- // 重新跳转目标页面(此时登录状态已满足)
- // router.push(router.currentRoute.fullPath);
- } else if (res && res.StatusCode === 403) {
- // 无权限 → 跳错误页
- isLogging = false;
- router.push('/error');
- } else if (res && res.StatusCode === 420) {
- // 需重新获取 code → 清除缓存并重定向
- isLogging = false;
- getQyCode(); // 你的获取企业微信二维码/授权链接的函数
- } else {
- isLogging = false;
- throw new Error(res && res.Message ? res.Message : '登录失败');
- }
- } catch (error) {
- isLogging = false;
- console.error('企业微信登录失败:', error);
- // 登录失败可提示用户或重试
- alert('登录失败,请刷新页面重试');
- }
- };
- export const getGuid = () => {
- return 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
- let r = Math.random() * 16 | 0,
- v = c == 'x' ? r : (r & 0x3 | 0x8);
- return v.toString(16);
- });
- }
- export const getQyCode = () => {
- window.localStorage.clear();
- let url, appid, agentid;
- // url = encodeURIComponent(process.env.VUE_APP_AUTHURL);
- url = encodeURIComponent(window.location.href);
- // console.log("-url=",url)
- appid = process.env.VUE_APP_APPID;
- agentid = process.env.VUE_APP_AGENTID;
- window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${url}&response_type=code&scope=snsapi_base&state=&agentid=${agentid}&t=${new Date().getTime()}#wechat_redirect`;
- }
- // utils/authLock.js
- export const authLock = {
- // 内存锁:实时判断
- isAuthorizing: false,
- // 初始化:从本地缓存恢复锁状态(防止页面刷新后锁失效)
- init() {
- const lock = window.localStorage.getItem('isWechatAuthorizing');
- this.isAuthorizing = lock === 'true';
- },
- // 加锁:同时更新内存和本地缓存
- lock() {
- this.isAuthorizing = true;
- window.localStorage.setItem('isWechatAuthorizing', 'true');
- },
- // 解锁:同时更新内存和本地缓存
- unlock() {
- this.isAuthorizing = false;
- window.localStorage.removeItem('isWechatAuthorizing');
- }
- };
- // 初始化锁
- authLock.init();
|