Sfoglia il codice sorgente

优化用户角色转换功能:添加空请求体参数;增强错误处理;实现用户角色实时查询

yourname 7 mesi fa
parent
commit
be5effa172

+ 1 - 1
client/admin/api/users.ts

@@ -89,7 +89,7 @@ export const UserAPI = {
 
   convertToStudent: async (userId: number): Promise<UserConvertResponse> => {
     try {
-      const response = await axios.post(`/users/${userId}/convert-to-student`);
+      const response = await axios.post(`/users/${userId}/convert-to-student`, {});
       return response.data;
     } catch (error) {
       throw error;

+ 6 - 2
client/admin/pages_users.tsx

@@ -6,6 +6,7 @@ import {
 import { useQuery } from '@tanstack/react-query';
 import dayjs from 'dayjs';
 import { UserAPI } from './api/users.ts';
+import { AxiosError } from "axios";
 
 const { Title } = Typography;
 
@@ -115,7 +116,10 @@ export const UsersPage = () => {
       refetch(); // 刷新用户列表
     } catch (error) {
       console.error('转为学员失败:', error);
-      message.error('操作失败,请重试');
+      if(error instanceof AxiosError)
+        message.error(error.response?.data.error || '操作失败,请重试');
+      else
+        message.error('操作失败,请重试');
     } finally {
       setConvertingId(null);
     }
@@ -143,7 +147,7 @@ export const UsersPage = () => {
       key: 'role',
       render: (role: string) => (
         <Tag color={role === 'admin' ? 'red' : 'blue'}>
-          {role === 'admin' ? '管理员' : '普通用户'}
+          {role }
         </Tag>
       ),
     },

+ 10 - 0
server/middlewares.ts

@@ -33,11 +33,21 @@ export interface Variables {
 export const withAuth = async (c: HonoContext<{ Variables: Variables }>, next: () => Promise<void>) => {
   try {
     const auth = c.get('auth')
+    const apiClient = c.get('apiClient');
     
     const token = c.req.header('Authorization')?.replace('Bearer ', '')
     if (token) {
       const userData = await auth.verifyToken(token)
       if (userData) {
+        
+        // 实时查询当前用户的角色
+        const userRole = await apiClient.database.table('users')
+        .where('id', userData.id)
+        .select('role')
+        .first()
+
+        userData.role = userRole.role;
+
         c.set('user', userData)
         await next()
         return

+ 8 - 0
server/routes_auth.ts

@@ -72,6 +72,14 @@ export function createAuthRoutes(withAuth: WithAuth) {
             latitude: latitude || null,
             longitude: longitude || null
           })
+
+          // 实时查询当前用户的角色
+          const userRole = await apiClient.database.table('users')
+          .where('id', result.user.id)
+          .select('role')
+          .first()
+
+          result.user.role = userRole.role;
         }
         
         return c.json({

+ 6 - 5
server/routes_users.ts

@@ -327,10 +327,11 @@ export function createUserRoutes(withAuth: WithAuth) {
       }
 
       const apiClient = c.get('apiClient')
-      const body = await c.req.json()
+      const body = await c.req.json().catch(() => {});
       
       // 验证必填字段
       const { expiresAt } = body
+      
       if (!expiresAt) {
         return c.json({ error: '缺少有效期参数' }, 400)
       }
@@ -353,14 +354,14 @@ export function createUserRoutes(withAuth: WithAuth) {
         .where('id', id)
         .update({
           role: 'student',
-          student_expires_at: expiresAt,
-          updated_at: new Date()
+          valid_until: expiresAt,
+          updated_at: apiClient.database.fn.now()
         })
 
       const updatedUser = await apiClient.database.table('users')
         .where('id', id)
-        .select('id', 'username', 'nickname', 'role', 'student_expires_at')
-        .first()
+        .select('id', 'username', 'nickname', 'role', 'valid_until')
+        .first() 
 
       return c.json({
         data: updatedUser,