wulf-pulse/app/api/admin/users/route.ts
root 9f912aed24 feat: add authentication, user management, and admin features
Added comprehensive authentication and authorization system:

Authentication System:
- Better Auth integration with session management
- Login/logout pages and API routes
- Middleware for route protection
- Auth utilities and client libraries

User Management:
- User list, detail, and invite pages
- User API endpoints (CRUD operations)
- Session management for users
- Profile settings page

Role-Based Access Control:
- Role management pages (list, create, edit)
- Permission system with granular controls
- Role assignment to users
- Role API endpoints

Admin Features:
- Audit log page for tracking system events
- Admin settings page
- Audit service for logging user actions

Additional Features:
- Quotes management pages and components
- SalesBldr API integration
- Email service for notifications

Configuration & Documentation:
- Updated docker-compose.yml
- MCP server configuration (mcp.json)
- CVE-2025-55182 security review documentation
- Standards guide and PRD documents
- Re-enabling authentication documentation

Database Migrations:
- 012: Auth tables (users, sessions, accounts, verifications)
- 013: Role tables (roles, permissions, role_permissions, user_roles)
- 014: Admin settings table

UI Updates:
- Updated dashboard layout
- Enhanced app layout with auth integration
2026-01-31 12:43:14 -05:00

129 lines
3.6 KiB
TypeScript

import { NextRequest, NextResponse } from "next/server";
import { Pool } from "pg";
import { requireAdmin, requireSuperAdmin } from "@/lib/auth-utils";
const pool = new Pool({
connectionString: process.env.DATABASE_URL,
});
// GET /api/admin/users - List all users
export async function GET(request: NextRequest) {
const { error } = await requireAdmin();
if (error) return error;
try {
const searchParams = request.nextUrl.searchParams;
const search = searchParams.get("search") || "";
const role = searchParams.get("role") || "";
const status = searchParams.get("status") || "";
const page = parseInt(searchParams.get("page") || "1");
const limit = parseInt(searchParams.get("limit") || "20");
const offset = (page - 1) * limit;
let query = `
SELECT
id, name, email, email_verified, image, role, banned,
banned_reason, ban_expires, requires_setup, created_at, updated_at
FROM "user"
WHERE 1=1
`;
const params: (string | number)[] = [];
let paramIndex = 1;
if (search) {
query += ` AND (name ILIKE $${paramIndex} OR email ILIKE $${paramIndex})`;
params.push(`%${search}%`);
paramIndex++;
}
if (role) {
query += ` AND role = $${paramIndex}`;
params.push(role);
paramIndex++;
}
if (status === "active") {
query += ` AND (banned = false OR banned IS NULL)`;
} else if (status === "banned") {
query += ` AND banned = true`;
}
// Get total count
const countQuery = query.replace(
/SELECT[\s\S]*?FROM/,
"SELECT COUNT(*) as total FROM"
);
const countResult = await pool.query(countQuery, params);
const total = parseInt(countResult.rows[0].total);
// Add pagination
query += ` ORDER BY created_at DESC LIMIT $${paramIndex} OFFSET $${paramIndex + 1}`;
params.push(limit, offset);
const result = await pool.query(query, params);
return NextResponse.json({
users: result.rows,
pagination: {
page,
limit,
total,
totalPages: Math.ceil(total / limit),
},
});
} catch (error) {
console.error("Error fetching users:", error);
return NextResponse.json(
{ error: "Failed to fetch users" },
{ status: 500 }
);
}
}
// POST /api/admin/users - Create a new user
export async function POST(request: NextRequest) {
const { session, error } = await requireSuperAdmin();
if (error) return error;
try {
const body = await request.json();
const { name, email, role = "user" } = body;
if (!name || !email) {
return NextResponse.json(
{ error: "Name and email are required" },
{ status: 400 }
);
}
// Check if user already exists
const existingUser = await pool.query(
'SELECT id FROM "user" WHERE email = $1',
[email]
);
if (existingUser.rows.length > 0) {
return NextResponse.json(
{ error: "User with this email already exists" },
{ status: 409 }
);
}
// Create the user
const id = crypto.randomUUID();
const result = await pool.query(
`INSERT INTO "user" (id, name, email, role, email_verified, created_at, updated_at)
VALUES ($1, $2, $3, $4, false, NOW(), NOW())
RETURNING id, name, email, role, email_verified, created_at`,
[id, name, email, role]
);
return NextResponse.json({ user: result.rows[0] }, { status: 201 });
} catch (error) {
console.error("Error creating user:", error);
return NextResponse.json(
{ error: "Failed to create user" },
{ status: 500 }
);
}
}