Skip to content

Commit

Permalink
🍋fix:还原更改cookies
Browse files Browse the repository at this point in the history
  • Loading branch information
durunsong committed Nov 20, 2024
1 parent f27189c commit a6aa553
Show file tree
Hide file tree
Showing 7 changed files with 66 additions and 4 deletions.
2 changes: 1 addition & 1 deletion .env.development
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ VITE_MODE = 'development'
## 变量必须以 VITE_ 为前缀才能暴露给外部读取

# 本地运行后端
VITE_BASE_API = 'http://localhost:4000'
VITE_BASE_API = 'http://localhost:4500'

# 部署到 vercel
# VITE_BASE_API = 'https://kilyicms-server.vercel.app'
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,11 @@
},
"dependencies": {
"@element-plus/icons-vue": "2.3.1",
"@types/js-cookie": "^3.0.6",
"@vue/compiler-dom": "3.5.4",
"axios": "1.7.7",
"element-plus": "2.8.2",
"js-cookie": "^3.0.5",
"lodash-es": "4.17.21",
"mitt": "3.0.1",
"moment": "^2.30.1",
Expand Down
11 changes: 11 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

13 changes: 11 additions & 2 deletions src/router/permission.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { usePermissionStoreHook } from "@/store/modules/permission";
import { ElMessage } from "element-plus";
import { setRouteChange } from "@/hooks/useRouteListener";
import { useTitle } from "@/hooks/useTitle";
import { getToken } from "@/utils/cache/cookies";
import routeSettings from "@/config/route";
import isWhiteList from "@/config/white-list";
import nprogress from "@/utils/nprogress";
Expand All @@ -13,9 +14,15 @@ router.beforeEach(async (to, _from, next) => {
nprogress.start();
const userStore = useUserStoreHook();
const permissionStore = usePermissionStoreHook();
const token = getToken();

// 如果在免登录的白名单中,则直接进入
if (isWhiteList(to)) return next();
// 如果没有登陆
if (!token) {
// 如果在免登录的白名单中,则直接进入
if (isWhiteList(to)) return next();
// 其他没有访问权限的页面将被重定向到登录页面
return next("/login");
}

// 如果已经登录,并准备进入 Login 页面,则重定向到主页
if (to.path === "/login") {
Expand All @@ -40,6 +47,8 @@ router.beforeEach(async (to, _from, next) => {
// 设置 replace: true, 因此导航将不会留下历史记录
next({ ...to, replace: true });
} catch (err: any) {
// 过程中发生任何错误,都直接重置 Token,并重定向到登录页面
userStore.resetToken();
ElMessage.error(err.message || "路由守卫过程发生错误");
next("/login");
}
Expand Down
17 changes: 17 additions & 0 deletions src/store/modules/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import store from "@/store";
import { defineStore } from "pinia";
import { useTagsViewStore } from "./tags-view";
import { useSettingsStore } from "./settings";
import { getToken, removeToken, setToken } from "@/utils/cache/cookies";
import { resetRouter } from "@/router";
import CACHE_KEY from "@/constants/cache-key";
import {
Expand All @@ -23,6 +24,7 @@ export const useUserStore: any = defineStore("user", () => {
const is_show_login_notice = getLocalData(CACHE_KEY.IS_SHOW_NOTICE) ?? false;
const is_show_login_notice_tips =
getLocalData(CACHE_KEY.IS_SHOW_NOTICE_TIPS) ?? false;
const token = ref<string>(getToken() || "");
const roles = ref<string[]>([]);
const user_name = ref<string>("");
const tagsViewStore = useTagsViewStore();
Expand All @@ -32,12 +34,16 @@ export const useUserStore: any = defineStore("user", () => {
const res: any = await loginApi({ user_name, password });
// 判断登录结果
if (res.status === 200) {
console.log("登录成功", res.token);

setToken(res.token);
// 登录成功notify标记
setLocalData(CACHE_KEY.IS_LOGIN_KEY, true);
} else {
showNotification(res.message, "warning");
return; // 如果登录失败,终止后续操作
}
token.value = res.token;
};

/** 获取用户角色详情 */
Expand Down Expand Up @@ -81,6 +87,7 @@ export const useUserStore: any = defineStore("user", () => {
const res: any = await loginApi(params);
// 判断登录结果
if (res.status === 200) {
setToken(res.token);
// 切换角色notification
setLocalData(CACHE_KEY.IS_SHOW_NOTICE, true);
setLocalData(CACHE_KEY.IS_SHOW_NOTICE_TIPS, true);
Expand Down Expand Up @@ -108,6 +115,7 @@ export const useUserStore: any = defineStore("user", () => {

/** 登出 */
const logout = () => {
removeToken();
removeLocalData(CACHE_KEY.USER_INFO);
setLocalData(CACHE_KEY.IS_SHOW_NOTICE, false);
setLocalData(CACHE_KEY.IS_LOGIN_KEY, false);
Expand All @@ -117,6 +125,13 @@ export const useUserStore: any = defineStore("user", () => {
_resetTagsView();
};

/** 重置 Token */
const resetToken = () => {
removeToken();
token.value = "";
roles.value = [];
};

/** 重置 Visited Views 和 Cached Views */
const _resetTagsView = () => {
if (!settingsStore.cacheTagsView) {
Expand All @@ -126,12 +141,14 @@ export const useUserStore: any = defineStore("user", () => {
};

return {
token,
roles,
user_name,
login,
getInfoRoles,
changeRoles,
logout,
resetToken,
};
});

Expand Down
15 changes: 15 additions & 0 deletions src/utils/cache/cookies.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
/** 统一处理 Cookie */
import CACHE_KEY from "@/constants/cache-key";
import Cookies from "js-cookie";

export const getToken = () => {
return Cookies.get(CACHE_KEY.TOKEN);
};

export const setToken = (token: string): any => {
Cookies.set(CACHE_KEY.TOKEN, token);
};

export const removeToken = () => {
Cookies.remove(CACHE_KEY.TOKEN);
};
10 changes: 9 additions & 1 deletion src/utils/request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import axios, {
import { ElNotification, ElLoading } from "element-plus";
import i18n from "@/i18n";
import { useUserStoreHook } from "@/store/modules/user";
import { getToken } from "@/utils/cache/cookies";
import router from "@/router";

/** 退出登录并强制刷新页面(会重定向到登录页) */
Expand All @@ -24,7 +25,7 @@ const pendingRequests: any = {};
const request = axios.create({
baseURL: import.meta.env.VITE_BASE_API, // 基础路径上会默认携带 VITE_BASE_API
timeout: 5000,
withCredentials: true,
// withCredentials: true, // 跨域请求时是否需要使用凭证
});

// 展示 loading
Expand Down Expand Up @@ -110,6 +111,13 @@ request.interceptors.request.use(
config.headers.set("Pragma", "no-cache");
config.headers.set("Expires", "0");

// 从 Cookie 中获取 token
const token = getToken();
// 如果 token 存在,将其添加到请求头中
if (token) {
config.headers.set("Authorization", `Bearer ${token}`); // 使用 set 方法
}

// 文件上传设置
if (config.headers.get("Content-Type") === "multipart/form-data") {
config.headers.set("Content-Type", "multipart/form-data");
Expand Down

0 comments on commit a6aa553

Please sign in to comment.