From dd9a30c94ef466659659fd84db99afb7837a704b Mon Sep 17 00:00:00 2001 From: carry <2641257231@qq.com> Date: Fri, 14 Feb 2025 22:57:08 +0800 Subject: [PATCH] =?UTF-8?q?=E5=AE=8C=E5=96=84=E4=BA=86login=E6=9C=BA?= =?UTF-8?q?=E5=88=B6=EF=BC=8C=E6=94=B9=E4=B8=BA=E4=BB=8Ejwt=E4=B8=AD?= =?UTF-8?q?=E8=A7=A3=E6=9E=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- package-lock.json | 9 +++++++++ package.json | 1 + src/store/userStore.ts | 10 ++++++---- 3 files changed, 16 insertions(+), 4 deletions(-) diff --git a/package-lock.json b/package-lock.json index 5a56c17..d68f7fd 100644 --- a/package-lock.json +++ b/package-lock.json @@ -10,6 +10,7 @@ "dependencies": { "axios": "^1.7.9", "element-plus": "^2.9.3", + "jwt-decode": "^4.0.0", "pinia": "^2.3.1", "pinia-plugin-persistedstate": "^4.2.0", "vue": "^3.5.13", @@ -2091,6 +2092,14 @@ "node": ">=6" } }, + "node_modules/jwt-decode": { + "version": "4.0.0", + "resolved": "https://registry.npmmirror.com/jwt-decode/-/jwt-decode-4.0.0.tgz", + "integrity": "sha512-+KJGIyHgkGuIq3IEBNftfhW/LfWhXUIY6OmyVWjliu5KH1y0fw7VQ8YndE2O4qZdMSd9SqbnC8GOcZEy0Om7sA==", + "engines": { + "node": ">=18" + } + }, "node_modules/klona": { "version": "2.0.6", "resolved": "https://registry.npmmirror.com/klona/-/klona-2.0.6.tgz", diff --git a/package.json b/package.json index 646c007..5fb88df 100644 --- a/package.json +++ b/package.json @@ -11,6 +11,7 @@ "dependencies": { "axios": "^1.7.9", "element-plus": "^2.9.3", + "jwt-decode": "^4.0.0", "pinia": "^2.3.1", "pinia-plugin-persistedstate": "^4.2.0", "vue": "^3.5.13", diff --git a/src/store/userStore.ts b/src/store/userStore.ts index 0ff4d3d..f74fe0a 100644 --- a/src/store/userStore.ts +++ b/src/store/userStore.ts @@ -3,6 +3,7 @@ import { ref } from 'vue'; import { authService } from '../api/authService'; import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'; import { createPinia } from 'pinia'; +import { jwtDecode } from 'jwt-decode'; // 创建 Pinia 实例并使用持久化插件 const pinia = createPinia(); @@ -35,11 +36,12 @@ export const useAuthStore = defineStore('auth', () => { // 用户登录方法,调用 authService.login 获取令牌并设置状态 async function login(usernameParam: string, password: string) { try { - const { access_token, refresh_token, role: userRole, username: userUsername, id: userIdValue } = await authService.login(usernameParam, password); + const { access_token, refresh_token } = await authService.login(usernameParam, password); + const decoded = jwtDecode<{ sub: string; role: string; username: string }>(access_token); setTokens({ access_token, refresh_token }); - setRole(userRole); - username.value = userUsername; - userId.value = userIdValue; + setRole(decoded.role); + username.value = decoded.username; + userId.value = parseInt(decoded.sub); } catch (error) { console.error('Login failed:', error); }