Files
mamad-app/app/api/admin/add-user/route.ts
2026-01-16 17:48:46 +02:00

96 lines
3.7 KiB
TypeScript

import { type NextRequest, NextResponse } from "next/server"
import { safeQuery } from "@/lib/database"
import { hashPassword } from "@/lib/auth"
import { type UserRole } from "@/types/user"
const hasManagedType = async (type: "field" | "department" | "team", name: string) => {
const rows = (await safeQuery("SELECT 1 FROM managed_types WHERE type = ? AND name = ? LIMIT 1", [
type,
name,
])) as any[]
if (rows.length > 0) {
return true
}
const legacyRows = (await safeQuery(`SELECT 1 FROM users WHERE ${type} = ? LIMIT 1`, [name])) as any[]
return legacyRows.length > 0
}
export async function POST(request: NextRequest) {
try {
const { name, isAdmin, field, department, team, role } = await request.json()
// Input validation
if (!name || !field || !department || !team) {
return NextResponse.json({ error: "נתונים חסרים" }, { status: 400 })
}
// Validate department, team, and field against managed types
if (!(await hasManagedType("field", field))) {
return NextResponse.json({ error: "Invalid field." }, { status: 400 })
}
if (!(await hasManagedType("department", department))) {
return NextResponse.json({ error: "Invalid department." }, { status: 400 })
}
if (!(await hasManagedType("team", team))) {
return NextResponse.json({ error: "Invalid team." }, { status: 400 })
}
const fieldRows = (await safeQuery("SELECT id FROM managed_types WHERE type = 'field' AND name = ?", [
field,
])) as Array<{ id: number }>
const departmentRows = (await safeQuery(
"SELECT id, parent_id AS parentId FROM managed_types WHERE type = 'department' AND name = ?",
[department],
)) as Array<{ id: number; parentId: number | null }>
const teamRows = (await safeQuery(
"SELECT id, parent_id AS parentId FROM managed_types WHERE type = 'team' AND name = ?",
[team],
)) as Array<{ id: number; parentId: number | null }>
if (fieldRows.length === 0 || departmentRows.length === 0 || teamRows.length === 0) {
return NextResponse.json({ error: "Invalid field, department, or team." }, { status: 400 })
}
if (departmentRows[0].parentId !== fieldRows[0].id) {
return NextResponse.json({ error: "Department does not belong to field." }, { status: 400 })
}
if (teamRows[0].parentId !== departmentRows[0].id) {
return NextResponse.json({ error: "Team does not belong to department." }, { status: 400 })
}
const validRoles: UserRole[] = ["user", "team_admin", "department_admin", "field_admin", "global_admin"]
// Set role based on isAdmin flag or explicit role
const userRole: UserRole = (role as UserRole) || (isAdmin ? "global_admin" : "user")
if (!validRoles.includes(userRole)) {
return NextResponse.json({ error: "תפקיד לא תקין" }, { status: 400 })
}
// Generate unique Login ID
const { generateUniqueIsraeliID } = await import("@/lib/auth")
const nationalId = await generateUniqueIsraeliID()
// Hash default password "password123"
const hashedPassword = await hashPassword("password123")
await safeQuery(
"INSERT INTO users (national_id, password, name, is_admin, role, must_change_password, field, department, team) VALUES (?, ?, ?, ?, ?, TRUE, ?, ?, ?)",
[nationalId, hashedPassword, name, isAdmin, userRole, field, department, team],
)
return NextResponse.json({
success: true,
nationalId: nationalId,
message: `משתמש ${name} נוסף בהצלחה עם מזהה: ${nationalId}`,
})
} catch (error) {
console.error("Add user error:", error)
return NextResponse.json({ error: "שגיאה בהוספת משתמש" }, { status: 500 })
}
}