Files
NextEdu/src/modules/settings/actions-password.ts
SpecialX 3b6272c99d feat: 完成 P1 全部功能 + 修复 proxy 导出 + 切换 MySQL 端口至 14013
## P1 功能(20 项)
- 站内消息系统、家长仪表盘、学生考勤管理
- Excel 导入导出、用户批量导入、成绩导出
- 排课规则+自动排课+课表调整
- 成绩趋势+对比分析、密码安全策略、速率限制
- 数据变更日志、文件预览+存储策略、全文检索
- 依赖审计集成 CI、数据库定时备份、E2E 测试完善
- 通知偏好管理

## 基础设施修复
- src/proxy.ts: 将 middleware 导出重命名为 proxy(Next.js 16 要求)
- .env: MySQL 端口从 13002 切换至 14013
- scripts/create-db.ts: 新增数据库初始化脚本

## 架构文档同步
- 004_architecture_impact_map.md 和 005_architecture_data.json
  完整记录所有新增表、模块、路由、权限、依赖关系
2026-06-17 13:44:37 +08:00

114 lines
3.8 KiB
TypeScript

"use server"
import { revalidatePath } from "next/cache"
import { eq } from "drizzle-orm"
import { compare, hash } from "bcryptjs"
import { db } from "@/shared/db"
import { users, passwordSecurity } from "@/shared/db/schema"
import type { ActionState } from "@/shared/types/action-state"
import { requireAuth, PermissionDeniedError } from "@/shared/lib/auth-guard"
import { validatePassword } from "@/shared/lib/password-policy"
import { rateLimit, rateLimitKey, RATE_LIMIT_RULES } from "@/shared/lib/rate-limit"
const normalizeBcryptHash = (value: string) => {
if (value.startsWith("$2")) return value
if (value.startsWith("$")) return `$2b${value}`
return `$2b$${value}`
}
/**
* Change the current user's password. Requires only authentication
* (no specific permission) since every user can manage their own
* credentials. Rate-limited to slow brute-force of the current password.
*/
export async function changePasswordAction(
prevState: ActionState<null>,
formData: FormData
): Promise<ActionState<null>> {
try {
const ctx = await requireAuth()
const userId = ctx.userId
const limitKey = rateLimitKey("pwd-change", userId)
const limit = rateLimit({ key: limitKey, ...RATE_LIMIT_RULES.PASSWORD_CHANGE })
if (!limit.success) {
return { success: false, message: "Too many attempts. Please try again later." }
}
const currentPassword = String(formData.get("currentPassword") ?? "")
const newPassword = String(formData.get("newPassword") ?? "")
const confirmPassword = String(formData.get("confirmPassword") ?? "")
if (!currentPassword || !newPassword || !confirmPassword) {
return { success: false, message: "All fields are required" }
}
if (newPassword !== confirmPassword) {
return { success: false, message: "New passwords do not match" }
}
if (newPassword === currentPassword) {
return { success: false, message: "New password must be different from current password" }
}
const validation = validatePassword(newPassword)
if (!validation.valid) {
return { success: false, message: validation.errors[0] ?? "Password does not meet requirements" }
}
const [user] = await db
.select({ id: users.id, password: users.password })
.from(users)
.where(eq(users.id, userId))
.limit(1)
if (!user || !user.password) {
return { success: false, message: "User not found or no password set" }
}
const storedHash = normalizeBcryptHash(user.password)
if (!storedHash.startsWith("$2")) {
return { success: false, message: "Stored password is invalid" }
}
const ok = await compare(currentPassword, storedHash)
if (!ok) {
return { success: false, message: "Current password is incorrect" }
}
const newHash = await hash(newPassword, 10)
const now = new Date()
await db
.update(users)
.set({ password: newHash, updatedAt: now })
.where(eq(users.id, userId))
const [existing] = await db
.select({ id: passwordSecurity.id })
.from(passwordSecurity)
.where(eq(passwordSecurity.userId, userId))
.limit(1)
if (existing) {
await db
.update(passwordSecurity)
.set({
lastPasswordChange: now,
passwordChangedAt: now,
mustChangePassword: false,
updatedAt: now,
})
.where(eq(passwordSecurity.userId, userId))
} else {
await db.insert(passwordSecurity).values({
userId,
lastPasswordChange: now,
passwordChangedAt: now,
mustChangePassword: false,
})
}
revalidatePath("/settings")
return { success: true, message: "Password changed successfully", data: null }
} catch (error) {
if (error instanceof PermissionDeniedError) return { success: false, message: error.message }
return { success: false, message: "Failed to change password" }
}
}