issue-ai/src/app/api/users/sync-emails/route.ts

44 lines
1.3 KiB
TypeScript

import { NextRequest, NextResponse } from 'next/server'
import { getDb } from '@/lib/db'
import { initDatabase } from '@/lib/db-schema'
import { getCurrentUser } from '@/lib/auth'
import { hasPermission } from '@/lib/permissions'
import { ldapGetUserInfo } from '@/lib/ldap'
import { writeAuditLog, getClientIP } from '@/lib/audit'
export async function POST(_request: NextRequest) {
initDatabase()
const user = await getCurrentUser()
if (!user) return NextResponse.json({ error: '未登录' }, { status: 401 })
if (!hasPermission(user, 'users:write')) return NextResponse.json({ error: '权限不足' }, { status: 403 })
const db = getDb()
const users = db.prepare(
'SELECT id, username FROM users WHERE email IS NULL OR email = \'\''
).all() as { id: number; username: string }[]
let synced = 0
let failed = 0
for (const u of users) {
const info = await ldapGetUserInfo(u.username)
if (info?.email) {
db.prepare('UPDATE users SET email = ? WHERE id = ?').run(info.email, u.id)
synced++
} else {
failed++
}
}
writeAuditLog({
userId: user.id,
apiKeyId: null,
action: 'sync_emails',
entityType: 'user',
details: { sync_emails: { synced, failed } },
ipAddress: getClientIP(_request)
})
return NextResponse.json({ synced, failed, total: users.length })
}