添加用户权限查询功能,解码JWT以获取用户ID,并根据权限更新用户权限状态

This commit is contained in:
keqingmoe 2024-12-31 00:28:51 +08:00
parent 08dfb27ac9
commit 78b6416e15

View File

@ -11,7 +11,7 @@
刷新
</v-btn>
<v-dialog v-model="dialog0" max-width="500px">
<template v-slot:activator="{ props }">
<template v-if="userPermission == '1'" v-slot:activator="{ props }">
<v-btn class="mb-2" color="primary" dark v-bind="props">
新建题目
</v-btn>
@ -124,6 +124,7 @@ import { useAuthStore } from '@/store/auth';
import axios, { Axios, AxiosError } from 'axios';
import { computed, nextTick, onMounted, ref, watch } from 'vue';
import * as mathjs from 'mathjs';
import { jwtDecode, type JwtPayload } from 'jwt-decode';
const loading = ref(false);
const refresh = async () => {
@ -278,6 +279,45 @@ watch(dialogDelete, (val) => {
const authStore = useAuthStore();
const storedToken = ref(authStore.token);
interface KqmJwt extends JwtPayload {
user_id: string;
};
const userId = computed(() => {
if (storedToken.value != '') {
let data: KqmJwt = jwtDecode(storedToken.value);
return data.user_id;
}
return '';
});
type UserPermissionResponse = { success?: string, permission?: string, error?: string };
const queryPermission = async () => {
try {
const formData = new FormData;
formData.append("user_id", userId.value);
let res = await axios.post('/api/auth/permission', formData);
return res.data as UserPermissionResponse;
} catch (e) {
let ex = e as AxiosError;
return ex.response?.data as UserPermissionResponse;
}
}
const userPermission = ref('');
const updateUserPermission = async () => {
let res = await queryPermission();
if (res?.success) {
userPermission.value = res.permission as string;
} else {
userPermission.value = '';
}
}
watch(userId, updateUserPermission, { immediate: true });
const decorate = <T>(ex: AxiosError) => {
if (ex.response?.data) {
return ex.response?.data as T;