ソースを参照

refactor: 对token配置进行重构、同时修复token获取失败的问题

小莫唐尼 9 ヶ月 前
コミット
d521a641de

+ 1 - 1
App.vue

@@ -1,5 +1,5 @@
 <script>
-import HaloTokenConfig from '@/config/token.config.js';
+import HaloTokenConfig from '@/config/uhalo.config.js';
 
 // app升级检测(搭配:https://ext.dcloud.net.cn/plugin?id=4470 升级中心)
 import CheckAppUpdate from '@/uni_modules/uni-upgrade-center-app/utils/check-update';

+ 14 - 16
api/v2/all.api.js

@@ -1,13 +1,11 @@
 /**
  * 所有的接口
  */
-import HaloTokenConfig from '@/config/token.config.js'
+import {getPersonalToken} from '@/utils/token.js'
 import HttpHandler from '@/common/http/request.js'
 import qs from 'qs'
 
-import {
-    getAppConfigs
-} from '@/config/index.js'
+import {getAppConfigs} from '@/config/index.js'
 
 export default {
     /**
@@ -44,14 +42,14 @@ export default {
      * @param {Object} params  查询参数
      */
     getCategoryList: (params) => {
-		const param = qs.stringify(params, {
-		    allowDots: true,
-		    encodeValuesOnly: true,
-		    skipNulls: true,
-		    encode: false,
-		    arrayFormat: 'repeat'
-		})
-        return HttpHandler.Get(`/apis/api.content.halo.run/v1alpha1/categories?${param}`,{})
+        const param = qs.stringify(params, {
+            allowDots: true,
+            encodeValuesOnly: true,
+            skipNulls: true,
+            encode: false,
+            arrayFormat: 'repeat'
+        })
+        return HttpHandler.Get(`/apis/api.content.halo.run/v1alpha1/categories?${param}`, {})
     },
     /**
      * 查询分类下的文章
@@ -112,7 +110,7 @@ export default {
     getMomentList: (params) => {
         return HttpHandler.Get(`/apis/moment.halo.run/v1alpha1/moments`, params, {
             custom: {
-                systemToken: HaloTokenConfig.systemToken
+                personalToken: getPersonalToken()
             }
         })
     },
@@ -131,7 +129,7 @@ export default {
     getPhotoGroupList: (params) => {
         return HttpHandler.Get(`/apis/core.halo.run/v1alpha1/photogroups`, params, {
             custom: {
-                systemToken: HaloTokenConfig.systemToken
+                personalToken: getPersonalToken()
             }
         })
     },
@@ -143,7 +141,7 @@ export default {
     getPhotoListByGroupName: (params) => {
         return HttpHandler.Get(`/apis/console.api.photo.halo.run/v1alpha1/photos`, params, {
             custom: {
-                systemToken: HaloTokenConfig.systemToken
+                personalToken: getPersonalToken()
             }
         })
     },
@@ -154,7 +152,7 @@ export default {
     getFriendLinkGroupList: (params) => {
         return HttpHandler.Get(`/apis/core.halo.run/v1alpha1/linkgroups`, params, {
             custom: {
-                systemToken: HaloTokenConfig.systemToken
+                personalToken: getPersonalToken()
             }
         })
     },

+ 1 - 1
common/http/index.js

@@ -10,7 +10,7 @@
  *  修改时间:
  */
 
-import HaloTokenConfig from '@/config/token.config.js'
+import HaloTokenConfig from '@/config/uhalo.config.js'
 import {
 	setInterceptors
 } from "./interceptors.js";

+ 119 - 135
common/http/interceptors.js

@@ -9,149 +9,133 @@
  *  修改人员:
  *  修改时间:
  */
-import {
-	getAdminAccessToken
-} from "@/utils/auth.js";
-import {
-	delCache,
-	setCache
-} from "@/utils/storage";
+import {delCache, setCache} from "@/utils/storage";
 
 const getCategoryNameByUrl = (url) => {
-	const reg = '(?<=/api/content/categories/).+(?=/posts)'
-	return url.match(reg)[0] || '无分类名'
+    const reg = '(?<=/api/content/categories/).+(?=/posts)'
+    return url.match(reg)[0] || '无分类名'
 }
 const showCategoryInputPasswordModal = (response, category) => {
-	uni.showModal({
-		title: `[ ${category} ] 分类已加密`, // TODO 这里应该获取分类的名字,可以在弹窗之前请求后台拿到所有分类根据分类code拿到名称,但是不会在这之前发送请求
-		content: '',
-		editable: true,
-		placeholderText: '请输入分类密码后访问',
-		confirmText: '验证密码',
-		cancelText: '暂不访问',
-		showCancel: true,
-		cancelColor: '#999999',
-		confirmColor: '#03a9f4',
-		success: (res) => {
-			if (res.confirm) {
-				// TODO 这里如果没有输入密码点击确认应该阻止窗口关闭,但是没找到方法
-				if (!res.content) {
-					uni.showToast({
-						title: '提示:请输入密码',
-						icon: 'none',
-						success: () => {
-							setTimeout(() => {
-								showCategoryInputPasswordModal(response, category);
-							}, 800)
-						}
-					})
-					return;
-				}
-				// 根据请求URL正则匹配分类code,然后把输入的密码根据分类code放入缓存,然后在category.getCategoryPostList中获取,解决多个分类加密输入密码后点错的问题
-				// 目前存在一个问题,比如前两个都需要密码,如果先输入第二个的密码之后,重新进来默认打开第一个还会弹窗,所以想在弹窗标题上增加分类名字
-				// 另外有以下两种方式科技解决
-				// TODO 1.其实这里获取到密码之后可以直接发送一个请求追加上password参数,因为后台会缓存权限,后续不输入密码也可以访问,可惜不会
-				// TODO 2.另外也可以拿到密码之后,直接选中该分类追加password参数,重新请求,可惜也不会
-				setCache('APP_CATEGORY_PWD_' + category, res.content)
-				uni.reLaunch({
-					url: '/pages/tabbar/category/category'
-				});
-			} else if (res.cancel) {}
-		},
-	})
+    uni.showModal({
+        title: `[ ${category} ] 分类已加密`, // TODO 这里应该获取分类的名字,可以在弹窗之前请求后台拿到所有分类根据分类code拿到名称,但是不会在这之前发送请求
+        content: '',
+        editable: true,
+        placeholderText: '请输入分类密码后访问',
+        confirmText: '验证密码',
+        cancelText: '暂不访问',
+        showCancel: true,
+        cancelColor: '#999999',
+        confirmColor: '#03a9f4',
+        success: (res) => {
+            if (res.confirm) {
+                // TODO 这里如果没有输入密码点击确认应该阻止窗口关闭,但是没找到方法
+                if (!res.content) {
+                    uni.showToast({
+                        title: '提示:请输入密码', icon: 'none', success: () => {
+                            setTimeout(() => {
+                                showCategoryInputPasswordModal(response, category);
+                            }, 800)
+                        }
+                    })
+                    return;
+                }
+                // 根据请求URL正则匹配分类code,然后把输入的密码根据分类code放入缓存,然后在category.getCategoryPostList中获取,解决多个分类加密输入密码后点错的问题
+                // 目前存在一个问题,比如前两个都需要密码,如果先输入第二个的密码之后,重新进来默认打开第一个还会弹窗,所以想在弹窗标题上增加分类名字
+                // 另外有以下两种方式科技解决
+                // TODO 1.其实这里获取到密码之后可以直接发送一个请求追加上password参数,因为后台会缓存权限,后续不输入密码也可以访问,可惜不会
+                // TODO 2.另外也可以拿到密码之后,直接选中该分类追加password参数,重新请求,可惜也不会
+                setCache('APP_CATEGORY_PWD_' + category, res.content)
+                uni.reLaunch({
+                    url: '/pages/tabbar/category/category'
+                });
+            } else if (res.cancel) {
+            }
+        },
+    })
 }
 
 export const setInterceptors = (http) => {
-	http.interceptors.request.use(
-		(config) => {
-			console.log("config", config)
+    http.interceptors.request.use((config) => {
+        console.log("config", config)
 
-			// 可使用async await 做异步操作
-			config.header = {
-				...config.header
-				// ... 可以直接加参数
-			};
-			if (config.custom.systemToken) {
-				config.header['Authorization'] = `Bearer ${config.custom.systemToken}`
-			}
-			return config;
-		},
-		(config) => {
-			// 可使用async await 做异步操作
-			return Promise.reject(config);
-		}
-	);
+        // 可使用async await 做异步操作
+        config.header = {
+            ...config.header
+            // ... 可以直接加参数
+        };
+        if (config.custom.personalToken) {
+            config.header['Authorization'] = `Bearer ${config.custom.personalToken}`
+        }
+        return config;
+    }, (config) => {
+        // 可使用async await 做异步操作
+        return Promise.reject(config);
+    });
 
-	http.interceptors.response.use(
-		(response) => {
-			/* 对响应成功做点什么 可使用async await 做异步操作*/
-			//  if (response.data.code !== 200) { // 服务端返回的状态码不等于200,则reject()
-			//    return Promise.reject(response) // return Promise.reject 可使promise状态进入catch
-			// if (response.config.custom.verification) { // 演示自定义参数的作用
-			//   return response.data
-			// } 
+    http.interceptors.response.use((response) => {
+        /* 对响应成功做点什么 可使用async await 做异步操作*/
+        //  if (response.data.code !== 200) { // 服务端返回的状态码不等于200,则reject()
+        //    return Promise.reject(response) // return Promise.reject 可使promise状态进入catch
+        // if (response.config.custom.verification) { // 演示自定义参数的作用
+        //   return response.data
+        // }
 
-			if (response.statusCode == 200) {
-				return response.data;
-			} else {
-				return Promise.reject(response);
-			}
-		},
-		(response) => {
-			/*  对响应错误做点什么 (statusCode !== 200)*/
-			if (!response.data) {
-				return Promise.reject({
-					status: 500,
-					message: 'API接口服务异常!'
-				})
-			} else if (response.data.status == 401) {
-				uni.$tm.toast(response.data.message);
-				// 如果是请求分类之后报401说明密码错误,那么清除该密码,下次点击会报403弹窗再次输入密码
-				if (response.config.url.indexOf('/api/content/categories') >= 0) {
-					const category = getCategoryNameByUrl(response.config.url)
-					delCache('APP_CATEGORY_PWD_' + category);
-					uni.showToast({
-						title: '提示:密码不正确',
-						icon: 'none',
-						success: () => {
-							setTimeout(() => {
-								showCategoryInputPasswordModal(response, category);
-							}, 800)
-						}
-					})
-				} else {
-					// 其他情况维持原来的逻辑
-					delCache('APP_ADMIN_LOGIN_TOKEN');
-					uni.$eShowModal({
-						title: '提示',
-						content: '您未登录超管账号或登录已过期,是否重新登录?',
-						showCancel: true,
-						cancelText: '否',
-						cancelColor: '#999999',
-						confirmText: '是',
-						confirmColor: '#03a9f4'
-					}).then(res => {
-						uni.navigateTo({
-							url: '/pagesB/login/login'
-						})
-					}).catch(err => {
-						uni.switchTab({
-							url: '/pages/tabbar/about/about'
-						})
-					})
-				}
-				return Promise.reject(response.data);
-			} else if (response.data.status == 403) {
-				// 如果报403是请求分类文章接口(您没有该分类的访问权限)的话说明是私密分类,需要输入密码请求
-				if (response.config.url.indexOf('/api/content/categories') >= 0) {
-					const category = getCategoryNameByUrl(response.config.url);
-					showCategoryInputPasswordModal(response, category);
-				}
-				return Promise.reject(response.data);
-			} else {
-				return Promise.reject(response.data);
-			}
+        if (response.statusCode == 200) {
+            return response.data;
+        } else {
+            return Promise.reject(response);
+        }
+    }, (response) => {
+        /*  对响应错误做点什么 (statusCode !== 200)*/
+        if (!response.data) {
+            return Promise.reject({
+                status: 500, message: 'API接口服务异常!'
+            })
+        } else if (response.data.status == 401) {
+            uni.$tm.toast(response.data.message);
+            // 如果是请求分类之后报401说明密码错误,那么清除该密码,下次点击会报403弹窗再次输入密码
+            if (response.config.url.indexOf('/api/content/categories') >= 0) {
+                const category = getCategoryNameByUrl(response.config.url)
+                delCache('APP_CATEGORY_PWD_' + category);
+                uni.showToast({
+                    title: '提示:密码不正确', icon: 'none', success: () => {
+                        setTimeout(() => {
+                            showCategoryInputPasswordModal(response, category);
+                        }, 800)
+                    }
+                })
+            } else {
+                // 其他情况维持原来的逻辑
+                delCache('APP_ADMIN_LOGIN_TOKEN');
+                uni.$eShowModal({
+                    title: '提示',
+                    content: '您未登录超管账号或登录已过期,是否重新登录?',
+                    showCancel: true,
+                    cancelText: '否',
+                    cancelColor: '#999999',
+                    confirmText: '是',
+                    confirmColor: '#03a9f4'
+                }).then(res => {
+                    uni.navigateTo({
+                        url: '/pagesB/login/login'
+                    })
+                }).catch(err => {
+                    uni.switchTab({
+                        url: '/pages/tabbar/about/about'
+                    })
+                })
+            }
+            return Promise.reject(response.data);
+        } else if (response.data.status == 403) {
+            // 如果报403是请求分类文章接口(您没有该分类的访问权限)的话说明是私密分类,需要输入密码请求
+            if (response.config.url.indexOf('/api/content/categories') >= 0) {
+                const category = getCategoryNameByUrl(response.config.url);
+                showCategoryInputPasswordModal(response, category);
+            }
+            return Promise.reject(response.data);
+        } else {
+            return Promise.reject(response.data);
+        }
 
-		}
-	);
-};
+    });
+};

+ 1 - 1
common/markdown/markdown.config.js

@@ -3,7 +3,7 @@
  */
 
 import {getAppConfigs} from '@/config/index.js'
-import HaloTokenConfig from '@/config/token.config.js'
+import HaloTokenConfig from '@/config/uhalo.config.js'
 import utils from '@/utils/index.js'
 
 export default {

+ 5 - 1
config/index.js

@@ -4,7 +4,11 @@ export const _AppMockJsonKey = 'APP_GLOBAL_MOCK_JSON';
 
 // 默认的应用设置
 export const DefaultAppConfigs = {
-    basicConfig: {},
+    basicConfig: {
+        tokenConfig: {
+            personalToken: "",
+        }
+    },
     loveConfig: {},
     imagesConfig: {},
     authorConfig: {},

+ 0 - 15
config/token.config.js

@@ -1,15 +0,0 @@
-import {getAppConfigs} from "@/config/index";
-
-/** 应用配置 */
-const UniHaloConfig = Object.freeze({
-
-	/** 基础请求域名:你的Halo博客基础域名 */
-	BASE_API: "",
-	// 比如:
-	// BASE_API: "https://blog.xiaoxiaomo.cn",
-
-	// token
-	systemToken: getAppConfigs()?.basicConfig?.tokenConfig?.personalToken,
-})
-
-export default UniHaloConfig;

+ 12 - 0
config/uhalo.config.js

@@ -0,0 +1,12 @@
+/** 应用基础配置 */
+const UHaloBaseConfig = Object.freeze({
+
+    /** 基础请求域名:你的Halo博客基础域名 */
+    BASE_API: "",
+    // 示例:
+    // BASE_API: "https://blog.xiaoxiaomo.cn",
+
+    // todo:可能有其他配置
+})
+
+export default UHaloBaseConfig;

+ 1 - 1
main.js

@@ -58,7 +58,7 @@ Vue.prototype.$http = http;
 import ApiManager from '@/api/index.js'
 Vue.use(ApiManager);
 
-import HaloTokenConfig from '@/config/token.config.js'
+import HaloTokenConfig from '@/config/uhalo.config.js'
 Vue.prototype.$baseApiUrl = HaloTokenConfig.BASE_API
 
 // 由于微信小程序的运行机制问题,需声明如下一行,H5和APP非必填

+ 1 - 1
pagesA/article-detail/article-detail.vue

@@ -316,7 +316,7 @@ import {
   getRestrictReadTypeName,
   getShowableContent
 } from "@/utils/restrictRead";
-import HaloTokenConfig from "@/config/token.config";
+import HaloTokenConfig from "@/config/uhalo.config";
 import RestrictReadSkeleton from "@/components/restrict-read-skeleton/restrict-read-skeleton.vue";
 import TmImages from "@/tm-vuetify/components/tm-images/tm-images.vue";
 import TmInput from "@/tm-vuetify/components/tm-input/tm-input.vue";

+ 6 - 0
store/config.js

@@ -8,6 +8,7 @@
 import {DefaultAppConfigs, getAppConfigs, getAppMockJson, setAppConfigs, setAppMockJson} from '@/config/index.js'
 import v2Config from '@/api/v2/all.config.js'
 import utils from '@/utils/index.js'
+import {setTokens} from "@/utils/token";
 
 export default {
     namespaced: true,
@@ -42,6 +43,11 @@ export default {
                     const res = await v2Config.getAppConfigs()
                     if (res) {
                         commit('setConfigs', utils.deepMerge(DefaultAppConfigs, res))
+
+                        // 存储token
+                        if (res?.basicConfig?.tokenConfig) {
+                            setTokens(res.basicConfig.tokenConfig)
+                        }
                         resolve(res)
                     } else {
                         dispatch("setDefaultAppSettings");

+ 1 - 1
utils/index.js

@@ -10,7 +10,7 @@
  *  修改时间:
  */
 
-import HaloTokenConfig from '@/config/token.config.js'
+import HaloTokenConfig from '@/config/uhalo.config.js'
 import {getAppConfigs} from '@/config/index.js'
 
 const utils = {

+ 22 - 22
utils/storage.js

@@ -1,39 +1,39 @@
 /**
  * 设置缓存
- * @param {缓存key} key
- * @param {需要存储的缓存值} value
- * @param {过期时间,默认0表示永久有效} expire
+ * @param {string} key 缓存key
+ * @param {Object} value 需要存储的缓存值
+ * @param {number} expire 过期时间,默认0表示永久有效
  */
 export const setCache = (key, value, expire = 0) => {
-	let obj = {
-		data: value, //存储的数据
-		time: Date.now() / 1000, //记录存储的时间戳
-		expire: expire //记录过期时间,单位秒
-	}
-	uni.setStorageSync(key, JSON.stringify(obj))
+    let obj = {
+        data: value, //存储的数据
+        time: Date.now() / 1000, //记录存储的时间戳
+        expire: expire //记录过期时间,单位秒
+    }
+    uni.setStorageSync(key, JSON.stringify(obj))
 }
 
 /**
  * 获取缓存
- * @param {缓存key} key
+ * @param {string} key
  */
 export const getCache = (key) => {
-	let val = uni.getStorageSync(key)
-	if (!val) {
-		return null
-	}
-	val = JSON.parse(val)
-	if (val.expire && Date.now() / 1000 - val.time > val.expire) {
-		uni.removeStorageSync(key)
-		return null
-	}
-	return val.data
+    let val = uni.getStorageSync(key)
+    if (!val) {
+        return null
+    }
+    val = JSON.parse(val)
+    if (val.expire && Date.now() / 1000 - val.time > val.expire) {
+        uni.removeStorageSync(key)
+        return null
+    }
+    return val.data
 }
 
 /**
  * 删除缓存
- * @param {缓存key} key
+ * @param { string } key 缓存key
  */
 export const delCache = (key) => {
-	uni.removeStorageSync(key)
+    uni.removeStorageSync(key)
 }

+ 52 - 0
utils/token.js

@@ -0,0 +1,52 @@
+import {getCache, setCache} from "./storage";
+import utils from "./index"
+
+export const APP_TOKENS_KEY = "APP_TOKENS";
+
+
+/**
+ * 获取 tokens
+ */
+export function getTokens() {
+    const tokens = getCache(APP_TOKENS_KEY);
+    return tokens ?? null;
+}
+
+/**
+ * 设置 tokens
+ */
+export function setTokens(value) {
+    setCache(APP_TOKENS_KEY, value);
+    return true;
+}
+
+/**
+ * 设置 tokens
+ */
+export function updateTokens(value) {
+    if (!value) return false
+    const tokens = getTokens(APP_TOKENS_KEY);
+    if (!tokens) return false
+    setTokens(utils.deepMerge(tokens, value))
+    return true
+}
+
+/**
+ * 获取 系统token
+ */
+export function getPersonalToken() {
+    const tokens = getTokens(APP_TOKENS_KEY);
+    console.log("tokens", tokens)
+    return tokens?.personalToken;
+}
+
+/**
+ * 设置 系统token
+ */
+export function setPersonalToken(personalToken) {
+    const tokens = getCache(APP_TOKENS_KEY);
+    if (!tokens) return false
+    tokens.personalToken = personalToken
+    updateTokens(tokens)
+    return true
+}