Files
NextEdu/src/modules/settings/actions-password.ts
SpecialX 49291fcc31 refactor: fix all P0/P1/P2 bugs and architecture issues
Bug fixes (from bugs/ directory):

- Fix cross-module DB queries in 9 modules (homework, grades, parent, diagnostic, elective, proctoring, notifications, scheduling, classes) by routing through data-access functions

- Fix shared/lib <-> auth circular dependency via new session.ts module

- Fix divide-by-zero guard in grades data-access

- Fix audit export data truncation (paginated fetch for full datasets)

- Fix missing transactions in homework grading and elective lottery

- Fix missing revalidatePath in course-plans actions

- Fix frontend permission checks using requirePermission instead of requireAuth

- Fix dashboard role routing using session.user.roles

- Fix student auth pattern (migrate getDemoStudentUser to users module)

- Fix ActionState return type handling in components

Code quality fixes:

- Remove 60+ as type assertions (replace with type guards)

- Remove non-null assertions (use optional chaining or explicit checks)

- Convert dynamic imports to static imports (grades, diagnostic)

- Add React.cache() wrapping for read functions

- Parallelize independent queries with Promise.all

- Add explicit return types to 30+ arrow functions

- Replace any with unknown + type guards

- Fix import type for type-only imports

- Add Zod validation schemas for classes and diagnostic modules

- Extract duplicate code (normalizeRoleName, normalizeBcryptHash, logger IP extraction)

- Add console.error to silent catch blocks

- Fix permission naming consistency (exam:proctor_read -> exam:proctor:read)

Architecture doc sync:

- Update 004_architecture_impact_map.md and 005_architecture_data.json

- Update management-modules-audit.md for P0-7 cross-module fix

Moved deleted proctoring event route to deletes/ folder.
2026-06-19 05:13:34 +08:00

102 lines
3.6 KiB
TypeScript

"use server"
import { revalidatePath } from "next/cache"
import { compare, hash } from "bcryptjs"
import { z } from "zod"
import type { ActionState } from "@/shared/types/action-state"
import { requirePermission, PermissionDeniedError } from "@/shared/lib/auth-guard"
import { Permissions } from "@/shared/types/permissions"
import { validatePassword } from "@/shared/lib/password-policy"
import { rateLimit, rateLimitKey, RATE_LIMIT_RULES } from "@/shared/lib/rate-limit"
import { normalizeBcryptHash } from "@/shared/lib/bcrypt-utils"
import {
getPasswordSecurityByUserId,
getUserPasswordHash,
updateUserPassword,
upsertPasswordSecurityOnPasswordChange,
} from "./data-access"
const ChangePasswordSchema = z.object({
currentPassword: z.string().min(1, "Current password is required"),
newPassword: z.string().min(1, "New password is required"),
confirmPassword: z.string().min(1, "Password confirmation is required"),
})
/**
* Change the current user's password. Requires self-service profile update
* permission (every authenticated user has it). 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 requirePermission(Permissions.USER_PROFILE_UPDATE)
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 parsed = ChangePasswordSchema.safeParse({
currentPassword: formData.get("currentPassword"),
newPassword: formData.get("newPassword"),
confirmPassword: formData.get("confirmPassword"),
})
if (!parsed.success) {
return {
success: false,
message: parsed.error.issues[0]?.message ?? "Invalid form data",
}
}
const { currentPassword, newPassword, confirmPassword } = parsed.data
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" }
}
// Parallelize user and passwordSecurity queries
const [userRecord, existingSecurity] = await Promise.all([
getUserPasswordHash(userId),
getPasswordSecurityByUserId(userId),
])
if (!userRecord || !userRecord.password) {
return { success: false, message: "User not found or no password set" }
}
const storedHash = normalizeBcryptHash(userRecord.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 updateUserPassword(userId, newHash, now)
await upsertPasswordSecurityOnPasswordChange(userId, now, existingSecurity)
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" }
}
}