feat: 实现用户登录认证与权限控制系统

- 新增用户登录页面与API端点(/api/auth/login、/api/auth/logout、/api/auth/me)
- 引入基于密码哈希的认证机制,支持默认管理员账号登录
- 创建访问控制模块(lib/access-control.ts),实现基于角色的权限验证
- 在现有API端点中集成权限检查,限制非管理员用户只能访问其所属项目数据
- 更新应用布局,要求用户登录后才能访问主界面
- 扩展用户表结构,增加用户名和密码哈希字段
- 调整项目、KR、目标、会议记录等资源的查询逻辑,根据用户权限过滤数据
- 改进管理页面(指标、模板)的删除操作,使用确认对话框替代直接确认
- 优化“我的KR”页面,为管理员提供全员KR概览视图
- 修复.gitignore文件中的拼写错误(.trae → .travis)
- 添加数据库迁移脚本,支持任务直接关联项目、禁用RLS、添加求助字段等
- 配置Next.js以支持独立输出和子路径部署
This commit is contained in:
2026-01-28 12:57:36 +08:00
parent e3e5e89df6
commit 7948b1afc7
50 changed files with 9506 additions and 150 deletions

View File

@@ -18,6 +18,16 @@ import type { Metric } from '@/types/database';
import { toast } from 'sonner';
import { Plus, Pencil, Trash2, Gauge, Loader2, TrendingUp, TrendingDown } from 'lucide-react';
import { getErrorMessage } from '@/lib/error-utils';
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from '@/components/ui/alert-dialog';
const metricSchema = z.object({
name: z.string().min(1, '名称不能为空'),
@@ -35,6 +45,9 @@ export default function AdminMetricsPage() {
const [isDialogOpen, setIsDialogOpen] = useState(false);
const [editingMetric, setEditingMetric] = useState<Metric | null>(null);
const [isSubmitting, setIsSubmitting] = useState(false);
const [deleteMetricId, setDeleteMetricId] = useState<string | null>(null);
const [isDeleteOpen, setIsDeleteOpen] = useState(false);
const [isDeleting, setIsDeleting] = useState(false);
const form = useForm<MetricFormValues>({
resolver: zodResolver(metricSchema),
@@ -121,17 +134,26 @@ export default function AdminMetricsPage() {
}
};
const handleDelete = async (metricId: string) => {
if (!confirm('确定要删除此指标吗?')) return;
const requestDelete = (metricId: string) => {
setDeleteMetricId(metricId);
setIsDeleteOpen(true);
};
const confirmDelete = async () => {
if (!deleteMetricId) return;
setIsDeleting(true);
try {
const res = await fetch(`/api/metrics/${metricId}`, { method: 'DELETE' });
const res = await fetch(`/api/metrics/${deleteMetricId}`, { method: 'DELETE' });
if (!res.ok) throw new Error('删除失败');
toast.success('指标已删除');
fetchMetrics();
} catch (error) {
toast.error(getErrorMessage(error));
} finally {
setIsDeleting(false);
setIsDeleteOpen(false);
setDeleteMetricId(null);
}
};
@@ -309,7 +331,7 @@ export default function AdminMetricsPage() {
<Button variant="ghost" size="sm" onClick={() => handleEdit(metric)}>
<Pencil className="h-4 w-4" />
</Button>
<Button variant="ghost" size="sm" onClick={() => handleDelete(metric.id)}>
<Button variant="ghost" size="sm" onClick={() => requestDelete(metric.id)}>
<Trash2 className="h-4 w-4 text-rose-500" />
</Button>
</TableCell>
@@ -327,6 +349,27 @@ export default function AdminMetricsPage() {
</Table>
</CardContent>
</Card>
<AlertDialog open={isDeleteOpen} onOpenChange={setIsDeleteOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>确认删除指标?</AlertDialogTitle>
<AlertDialogDescription>
删除后无法恢复。
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel disabled={isDeleting}>取消</AlertDialogCancel>
<AlertDialogAction
className="bg-rose-600 hover:bg-rose-700"
onClick={confirmDelete}
disabled={isDeleting}
>
{isDeleting ? '删除中...' : '确认删除'}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
);
}

View File

@@ -18,6 +18,16 @@ import type { Template } from '@/types/database';
import { toast } from 'sonner';
import { Plus, Pencil, Trash2, Files, Loader2, X } from 'lucide-react';
import { getErrorMessage } from '@/lib/error-utils';
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from '@/components/ui/alert-dialog';
const templateItemSchema = z.object({
title: z.string().min(1, '标题不能为空'),
@@ -44,6 +54,9 @@ export default function AdminTemplatesPage() {
const [isDialogOpen, setIsDialogOpen] = useState(false);
const [editingTemplate, setEditingTemplate] = useState<Template | null>(null);
const [isSubmitting, setIsSubmitting] = useState(false);
const [deleteTemplateId, setDeleteTemplateId] = useState<string | null>(null);
const [isDeleteOpen, setIsDeleteOpen] = useState(false);
const [isDeleting, setIsDeleting] = useState(false);
const form = useForm<TemplateFormValues>({
resolver: zodResolver(templateSchema),
@@ -135,17 +148,26 @@ export default function AdminTemplatesPage() {
}
};
const handleDelete = async (templateId: string) => {
if (!confirm('确定要删除此模板吗?')) return;
const requestDelete = (templateId: string) => {
setDeleteTemplateId(templateId);
setIsDeleteOpen(true);
};
const confirmDelete = async () => {
if (!deleteTemplateId) return;
setIsDeleting(true);
try {
const res = await fetch(`/api/templates/${templateId}`, { method: 'DELETE' });
const res = await fetch(`/api/templates/${deleteTemplateId}`, { method: 'DELETE' });
if (!res.ok) throw new Error('删除失败');
toast.success('模板已删除');
fetchTemplates();
} catch (error) {
toast.error(getErrorMessage(error));
} finally {
setIsDeleting(false);
setIsDeleteOpen(false);
setDeleteTemplateId(null);
}
};
@@ -395,7 +417,7 @@ export default function AdminTemplatesPage() {
<Button variant="ghost" size="sm" onClick={() => handleEdit(template)}>
<Pencil className="h-4 w-4" />
</Button>
<Button variant="ghost" size="sm" onClick={() => handleDelete(template.id)}>
<Button variant="ghost" size="sm" onClick={() => requestDelete(template.id)}>
<Trash2 className="h-4 w-4 text-rose-500" />
</Button>
</div>
@@ -431,6 +453,27 @@ export default function AdminTemplatesPage() {
</div>
)}
</div>
<AlertDialog open={isDeleteOpen} onOpenChange={setIsDeleteOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>确认删除模板?</AlertDialogTitle>
<AlertDialogDescription>
删除后无法恢复。
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel disabled={isDeleting}>取消</AlertDialogCancel>
<AlertDialogAction
className="bg-rose-600 hover:bg-rose-700"
onClick={confirmDelete}
disabled={isDeleting}
>
{isDeleting ? '删除中...' : '确认删除'}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
);
}

View File

@@ -18,10 +18,22 @@ import type { User } from '@/types/database';
import { toast } from 'sonner';
import { getErrorMessage } from '@/lib/error-utils';
import { Plus, Pencil, Trash2, Users, Loader2, Crown, Briefcase, User as UserIcon } from 'lucide-react';
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from '@/components/ui/alert-dialog';
const userSchema = z.object({
name: z.string().min(1, '名称不能为空'),
role: z.enum(['owner', 'pm', 'member']),
username: z.string().min(1, '账号不能为空'),
password: z.string().optional(),
});
type UserFormValues = z.infer<typeof userSchema>;
@@ -38,25 +50,41 @@ export default function AdminUsersPage() {
const [isDialogOpen, setIsDialogOpen] = useState(false);
const [editingUser, setEditingUser] = useState<User | null>(null);
const [isSubmitting, setIsSubmitting] = useState(false);
const [deleteUserId, setDeleteUserId] = useState<string | null>(null);
const [isDeleteOpen, setIsDeleteOpen] = useState(false);
const [isDeleting, setIsDeleting] = useState(false);
const form = useForm<UserFormValues>({
resolver: zodResolver(userSchema),
defaultValues: {
name: '',
role: 'member',
username: '',
password: '',
},
});
const onSubmit = async (values: UserFormValues) => {
setIsSubmitting(true);
try {
if (!editingUser && !values.password) {
throw new Error('请设置初始密码');
}
const url = editingUser ? `/api/users/${editingUser.id}` : '/api/users';
const method = editingUser ? 'PATCH' : 'POST';
const payload = {
name: values.name,
role: values.role,
username: values.username,
password: values.password ? values.password : undefined,
};
const res = await fetch(url, {
method,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(values),
body: JSON.stringify(payload),
});
if (!res.ok) {
@@ -81,21 +109,33 @@ export default function AdminUsersPage() {
form.reset({
name: user.name,
role: user.role,
username: user.username || '',
password: '',
});
setIsDialogOpen(true);
};
const handleDelete = async (userId: string) => {
if (!confirm('确定要删除此用户吗?')) return;
const requestDelete = (userId: string) => {
setDeleteUserId(userId);
setIsDeleteOpen(true);
};
const confirmDelete = async () => {
if (!deleteUserId) return;
setIsDeleting(true);
try {
const res = await fetch(`/api/users/${userId}`, { method: 'DELETE' });
if (!res.ok) throw new Error('删除失败');
const res = await fetch(`/api/users/${deleteUserId}`, { method: 'DELETE' });
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data?.error || '删除失败');
toast.success('用户已删除');
refreshUsers();
} catch (error) {
toast.error(getErrorMessage(error));
} finally {
setIsDeleting(false);
setIsDeleteOpen(false);
setDeleteUserId(null);
}
};
@@ -151,6 +191,34 @@ export default function AdminUsersPage() {
)}
/>
<FormField
control={form.control}
name="username"
render={({ field }) => (
<FormItem>
<FormLabel>账号 *</FormLabel>
<FormControl>
<Input placeholder="输入登录账号" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="password"
render={({ field }) => (
<FormItem>
<FormLabel>{editingUser ? '重置密码' : '密码 *'}</FormLabel>
<FormControl>
<Input type="password" placeholder={editingUser ? '留空则不修改' : '输入初始密码'} {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="role"
@@ -197,6 +265,7 @@ export default function AdminUsersPage() {
<TableHeader>
<TableRow>
<TableHead>用户</TableHead>
<TableHead>账号</TableHead>
<TableHead>角色</TableHead>
<TableHead>创建时间</TableHead>
<TableHead className="text-right">操作</TableHead>
@@ -217,6 +286,9 @@ export default function AdminUsersPage() {
<span className="font-medium">{user.name}</span>
</div>
</TableCell>
<TableCell className="text-muted-foreground">
{user.username || '-'}
</TableCell>
<TableCell>
<div className="flex items-center gap-2">
<RoleIcon className="h-4 w-4 text-muted-foreground" />
@@ -233,8 +305,8 @@ export default function AdminUsersPage() {
<Button
variant="ghost"
size="sm"
onClick={() => handleDelete(user.id)}
disabled={user.id === currentUser?.id}
onClick={() => requestDelete(user.id)}
disabled={user.role === 'owner'}
>
<Trash2 className="h-4 w-4 text-rose-500" />
</Button>
@@ -246,6 +318,27 @@ export default function AdminUsersPage() {
</Table>
</CardContent>
</Card>
<AlertDialog open={isDeleteOpen} onOpenChange={setIsDeleteOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>确认删除用户?</AlertDialogTitle>
<AlertDialogDescription>
删除后无法恢复。
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel disabled={isDeleting}>取消</AlertDialogCancel>
<AlertDialogAction
className="bg-rose-600 hover:bg-rose-700"
onClick={confirmDelete}
disabled={isDeleting}
>
{isDeleting ? '删除中...' : '确认删除'}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
);
}