完善了login机制,改为从jwt中解析

This commit is contained in:
carry 2025-02-14 22:57:08 +08:00
parent eb3ebc2745
commit dd9a30c94e
3 changed files with 16 additions and 4 deletions

9
package-lock.json generated
View File

@ -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",

View File

@ -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",

View File

@ -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);
}