75 lines
1.8 KiB
TypeScript
75 lines
1.8 KiB
TypeScript
import { NextRequest, NextResponse } from "next/server"
|
|
import { getServerSession } from "next-auth"
|
|
import { authOptions } from "@/lib/auth"
|
|
import { prisma } from "@/lib/prisma"
|
|
|
|
// 检查是否为管理员
|
|
async function checkAdmin(userId: string) {
|
|
const user = await prisma.user.findUnique({
|
|
where: { id: userId },
|
|
select: { isAdmin: true }
|
|
})
|
|
return user?.isAdmin === true
|
|
}
|
|
|
|
// 获取登录日志
|
|
export async function GET(req: NextRequest) {
|
|
try {
|
|
const session = await getServerSession(authOptions)
|
|
|
|
if (!session?.user?.id) {
|
|
return NextResponse.json({ error: "未授权" }, { status: 401 })
|
|
}
|
|
|
|
// 检查管理员权限
|
|
const isAdmin = await checkAdmin(session.user.id)
|
|
if (!isAdmin) {
|
|
return NextResponse.json({ error: "无权限访问" }, { status: 403 })
|
|
}
|
|
|
|
const { searchParams } = new URL(req.url)
|
|
const limit = parseInt(searchParams.get("limit") || "100")
|
|
const page = parseInt(searchParams.get("page") || "1")
|
|
const skip = (page - 1) * limit
|
|
|
|
// 获取登录日志总数
|
|
const total = await prisma.loginLog.count()
|
|
|
|
// 获取登录日志列表
|
|
const logs = await prisma.loginLog.findMany({
|
|
orderBy: {
|
|
createdAt: 'desc',
|
|
},
|
|
take: limit,
|
|
skip,
|
|
select: {
|
|
id: true,
|
|
userId: true,
|
|
email: true,
|
|
userName: true,
|
|
ip: true,
|
|
userAgent: true,
|
|
success: true,
|
|
message: true,
|
|
createdAt: true,
|
|
}
|
|
})
|
|
|
|
return NextResponse.json({
|
|
logs,
|
|
pagination: {
|
|
total,
|
|
page,
|
|
limit,
|
|
totalPages: Math.ceil(total / limit),
|
|
}
|
|
})
|
|
} catch (error) {
|
|
console.error("获取登录日志失败:", error)
|
|
return NextResponse.json(
|
|
{ error: "获取登录日志失败" },
|
|
{ status: 500 }
|
|
)
|
|
}
|
|
}
|