Files
infohliadka/pages/api/admin/audit-logs.ts
Lukas Davidovic 860070a302 migrate from SQLite to PostgreSQL with Drizzle ORM
- Updated all packages to latest versions (React 19, Next.js 14.2.32)
- Replaced sqlite3 with pg and drizzle-orm dependencies
- Created complete PostgreSQL schema with relationships and indexes
- Migrated all API endpoints from SQLite to Drizzle queries
- Added database seeding with sample data
- Updated authentication to use bcrypt instead of pbkdf2
- Configured connection pooling for PostgreSQL
- Updated app version to 1.0.0
- All endpoints tested and working correctly
2025-09-06 12:56:33 +02:00

81 lines
2.6 KiB
TypeScript

import type { NextApiRequest, NextApiResponse } from "next"
import { db, schema } from '../../../lib/db/connection'
import { eq, and, desc, count } from 'drizzle-orm'
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method !== "GET") return res.status(405).json({ error: "Method not allowed" })
const { page = '1', limit = '50', action, resource_type, user_id } = req.query
try {
let whereConditions = []
if (action) {
whereConditions.push(eq(schema.auditLogs.action, action as string))
}
if (resource_type) {
whereConditions.push(eq(schema.auditLogs.resourceType, resource_type as string))
}
if (user_id) {
whereConditions.push(eq(schema.auditLogs.userId, parseInt(user_id as string)))
}
const offset = (parseInt(page as string) - 1) * parseInt(limit as string)
const limitInt = parseInt(limit as string)
// Get logs with user info
const logs = await db
.select({
id: schema.auditLogs.id,
userId: schema.auditLogs.userId,
userEmail: schema.users.email,
action: schema.auditLogs.action,
resourceType: schema.auditLogs.resourceType,
resourceId: schema.auditLogs.resourceId,
details: schema.auditLogs.details,
ipAddress: schema.auditLogs.ipAddress,
createdAt: schema.auditLogs.createdAt
})
.from(schema.auditLogs)
.leftJoin(schema.users, eq(schema.auditLogs.userId, schema.users.id))
.where(whereConditions.length > 0 ? and(...whereConditions) : undefined)
.orderBy(desc(schema.auditLogs.createdAt))
.limit(limitInt)
.offset(offset)
// Get total count for pagination
const [totalResult] = await db
.select({ count: count() })
.from(schema.auditLogs)
.where(whereConditions.length > 0 ? and(...whereConditions) : undefined)
const total = totalResult.count
const totalPages = Math.ceil(total / limitInt)
res.json({
logs: logs.map(log => ({
id: log.id,
user_id: log.userId,
user_email: log.userEmail,
action: log.action,
resource_type: log.resourceType,
resource_id: log.resourceId,
details: log.details ? JSON.parse(log.details) : null,
ip_address: log.ipAddress,
created_at: log.createdAt
})),
pagination: {
page: parseInt(page as string),
limit: limitInt,
total,
totalPages
}
})
} catch (error) {
console.error('Audit logs error:', error)
res.status(500).json({ error: "Failed to fetch audit logs" })
}
}