Files
top-tickets/src/app/api/ldap/directory/import/route.ts
T
ogrechkoandClaude Sonnet 5 cb12711e91 Add account management and LDAP login
Admins can now create local agent/admin accounts and configure LDAP
directly from the UI (Настройки → Аккаунты / LDAP), with login trying
LDAP first and falling back to the local password. This is the first
place users.role is actually enforced (requireAdminSession).

Fixed a bug in the generated 0005 migration: the INSERT into __new_users
selected auth_source from the old users table, which doesn't have that
column yet — caused drizzle-kit migrate to fail silently.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QcXH24ky6zjk2UyK5oZUPH
2026-07-27 08:56:08 +00:00

48 lines
1.6 KiB
TypeScript

export const runtime = "nodejs";
import { NextResponse } from "next/server";
import { z } from "zod";
import { requireAdminSession } from "@/lib/auth/require";
import { getLdapSettings } from "@/lib/auth/ldap-config";
import { searchLdapDirectory } from "@/lib/ldap/client";
import { findOrCreateUserFromLdap } from "@/lib/auth/users";
const importSchema = z.object({ emails: z.array(z.string().email()).min(1) });
export async function POST(request: Request) {
const { session, response } = await requireAdminSession();
if (!session) return response;
const settings = await getLdapSettings();
if (!settings) {
return NextResponse.json({ error: "LDAP не настроен" }, { status: 400 });
}
const body = await request.json().catch(() => null);
const parsed = importSchema.safeParse(body);
if (!parsed.success) {
return NextResponse.json({ error: "Invalid input" }, { status: 400 });
}
try {
const entries = await searchLdapDirectory();
const wanted = new Set(parsed.data.emails.map((e) => e.toLowerCase()));
const toImport = entries.filter((e) => wanted.has(e.email.toLowerCase()));
const imported = [];
for (const entry of toImport) {
const user = await findOrCreateUserFromLdap({
email: entry.email,
name: entry.name,
defaultRole: settings.defaultRole,
});
imported.push(user.email);
}
return NextResponse.json({ ok: true, imported });
} catch (err) {
const message = err instanceof Error ? err.message : "Unknown error";
return NextResponse.json({ error: `Не удалось импортировать: ${message}` }, { status: 502 });
}
}