feat: 重构用户角色系统为管理员标识

- 将用户角色字段从role改为is_admin布尔值
- 更新相关API权限检查逻辑
- 修改数据库schema和迁移文件
- 调整前端用户显示逻辑
- 添加API响应工具函数
- 优化权限检查中间件
- 重构英雄组件为原子组件
This commit is contained in:
张翔
2026-03-12 20:45:43 +08:00
parent b207bfa7af
commit f357330ba8
22 changed files with 1078 additions and 552 deletions
+16 -17
View File
@@ -1,38 +1,37 @@
import { auth } from '../auth';
import { hasPermission, Role, Resource, Action } from './permissions';
import { isAdminUser } from './permissions';
export async function checkPermission(
resource: Resource,
action: Action
): Promise<{ allowed: boolean; userId?: string; role?: Role }> {
export async function checkIsAdmin(): Promise<{ isAdmin: boolean; userId?: string }> {
const session = await auth();
if (!session || !session.user) {
return { allowed: false };
return { isAdmin: false };
}
const userRole = session.user.role as Role;
const allowed = hasPermission(userRole, resource, action);
const isAdmin = isAdminUser(session.user.isAdmin as boolean | undefined);
return {
allowed,
isAdmin,
userId: session.user.id,
role: userRole,
};
}
export async function requirePermission(
resource: Resource,
action: Action
): Promise<{ userId: string; role: Role }> {
const result = await checkPermission(resource, action);
export async function requireAdmin(): Promise<{ userId: string }> {
const result = await checkIsAdmin();
if (!result.allowed) {
if (!result.isAdmin) {
throw new Error('无权限执行此操作');
}
return {
userId: result.userId!,
role: result.role!,
};
}
export async function getAdminUserId(): Promise<string | null> {
const session = await auth();
if (!session?.user) {
return null;
}
return session.user.id;
}
+2 -37
View File
@@ -1,38 +1,3 @@
export const PERMISSIONS = {
admin: {
content: ['create', 'read', 'update', 'delete', 'publish'],
config: ['read', 'update'],
users: ['create', 'read', 'update', 'delete'],
logs: ['read'],
},
editor: {
content: ['create', 'read', 'update', 'publish'],
config: ['read'],
users: [],
logs: ['read'],
},
viewer: {
content: ['read'],
config: ['read'],
users: [],
logs: [],
},
} as const;
export type Role = keyof typeof PERMISSIONS;
export type Resource = keyof typeof PERMISSIONS.admin;
export type Action = 'create' | 'read' | 'update' | 'delete' | 'publish';
export function hasPermission(
role: Role,
resource: Resource,
action: Action
): boolean {
const permissions = PERMISSIONS[role];
if (!permissions) return false;
const resourcePermissions = permissions[resource];
if (!resourcePermissions) return false;
return resourcePermissions.includes(action as never);
export function isAdminUser(isAdmin: boolean | undefined): boolean {
return isAdmin === true;
}