Skip to content

Commit

Permalink
🌶feat:后端操作cookie/前端修改
Browse files Browse the repository at this point in the history
  • Loading branch information
durunsong committed Nov 19, 2024
1 parent 0595339 commit f27189c
Show file tree
Hide file tree
Showing 8 changed files with 17 additions and 81 deletions.
2 changes: 0 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,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 All @@ -43,7 +42,6 @@
},
"devDependencies": {
"@iconify/json": "^2.2.261",
"@types/js-cookie": "3.0.6",
"@types/lodash-es": "4.17.12",
"@types/node": "22.5.4",
"@types/nprogress": "0.2.3",
Expand Down
11 changes: 0 additions & 11 deletions pnpm-lock.yaml

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

4 changes: 3 additions & 1 deletion src/layouts/components/NavigationBar/index.vue
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,8 @@ import { useLayoutMode } from "@/hooks/useLayoutMode";
import { useI18n } from "vue-i18n";
import CACHE_KEY from "@/constants/cache-key";
import { getLocalData } from "@/utils/cache/local-storage";
import { useRouter } from "vue-router";
const router = useRouter();
const { t } = useI18n();
const { isMobile } = useDevice();
Expand Down Expand Up @@ -132,7 +134,7 @@ const toggleSidebar = () => {
/** 登出 */
const logout = () => {
userStore.logout();
window.location.reload();
router.push("/login");
};
</script>

Expand Down
13 changes: 2 additions & 11 deletions src/router/permission.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ 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 @@ -14,15 +13,9 @@ router.beforeEach(async (to, _from, next) => {
nprogress.start();
const userStore = useUserStoreHook();
const permissionStore = usePermissionStoreHook();
const token = getToken();

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

// 如果已经登录,并准备进入 Login 页面,则重定向到主页
if (to.path === "/login") {
Expand All @@ -47,8 +40,6 @@ 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
4 changes: 4 additions & 0 deletions src/service/login.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,10 @@ export const registerApi = (params: RegisterRequestData) =>
data: params,
});

// logout
export const logoutApi = () =>
request({ url: "/api/users/logout", method: "GET" });

// userInfo
export const userInfoApi = () =>
request({ url: "/api/users/userInfo", method: "GET" });
16 changes: 1 addition & 15 deletions src/store/modules/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ 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 @@ -24,7 +23,6 @@ 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 @@ -34,14 +32,12 @@ export const useUserStore: any = defineStore("user", () => {
const res: any = await loginApi({ user_name, password });
// 判断登录结果
if (res.status === 200) {
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 @@ -85,7 +81,6 @@ 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 @@ -113,22 +108,15 @@ 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);
removeLocalData(CACHE_KEY.IS_SHOW_NOTICE_TIPS);
token.value = "";
roles.value = [];
resetRouter();
_resetTagsView();
};
/** 重置 Token */
const resetToken = () => {
removeToken();
token.value = "";
roles.value = [];
};

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

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

Expand Down
13 changes: 0 additions & 13 deletions src/utils/cache/cookies.ts

This file was deleted.

35 changes: 7 additions & 28 deletions src/utils/request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,15 @@ import axios, {
} from "axios";
import { ElNotification, ElLoading } from "element-plus";
import i18n from "@/i18n";
// import CACHE_KEY from "@/constants/cache-key";
import { getToken } from "@/utils/cache/cookies";
import { useUserStoreHook } from "@/store/modules/user";
import router from "@/router";

/** 退出登录并强制刷新页面(会重定向到登录页) */
const logout = () => {
useUserStoreHook().logout();
setTimeout(() => {
router.push("/login");
}, 2000);
};

const { t } = i18n.global;
Expand All @@ -22,6 +24,7 @@ const pendingRequests: any = {};
const request = axios.create({
baseURL: import.meta.env.VITE_BASE_API, // 基础路径上会默认携带 VITE_BASE_API
timeout: 5000,
withCredentials: true,
});

// 展示 loading
Expand Down Expand Up @@ -107,14 +110,6 @@ 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 All @@ -140,19 +135,15 @@ request.interceptors.response.use(
removePendingRequest(response.config);

// 检查后端返回的 requiresRelogin 字段
console.log("requiresRelogin", response.data);
if (response.data?.requiresRelogin) {
// 退出登录并重定向到登录页面
logout();
// 弹出提示重新登录
ElNotification({
message: "用户信息已更新,请重新登录!",
type: "warning",
duration: 1.5 * 1000,
});
setTimeout(() => {
window.location.reload();
}, 1500);
// 退出登录并重定向到登录页面
logout();
return Promise.reject(new Error("用户信息已更新,请重新登录!"));
}

Expand All @@ -170,18 +161,6 @@ request.interceptors.response.use(
// Token 过期时,尝试刷新 Token
case 401: {
errorInfo = t("case_401");
// const refreshToken = setToken(CACHE_KEY.REFRESH_TOKEN);
// if (refreshToken && !originalRequest._retry) {
// originalRequest._retry = true;
// // 实现刷新 token 的逻辑
// const newToken = await refreshAccessToken(refreshToken);
// setToken(newToken);
// originalRequest.headers["Authorization"] = `Bearer ${newToken}`;
// return request(originalRequest); // 重新发起请求
// } else {
// // 退出登录
// logout();
// }
// 退出登录
logout();
break;
Expand Down

0 comments on commit f27189c

Please sign in to comment.