Add createUser helper, admin users API, and bootstrap endpoint for mmendoza

This commit is contained in:
2026-06-27 16:47:02 -05:00
parent 1148f7a72f
commit 1bd5325baa
5 changed files with 50 additions and 137 deletions
+23
View File
@@ -0,0 +1,23 @@
import { NextRequest, NextResponse } from 'next/server';
import { requireRole, createUser } from '@/lib/auth';
export async function POST(request: NextRequest) {
try {
await requireRole('admin');
const body = await request.json();
const { username, password, role = 'user' } = body;
if (!username || !password) {
return NextResponse.json({ error: 'Username and password are required' }, { status: 400 });
}
if (role !== 'admin' && role !== 'user') {
return NextResponse.json({ error: 'Role must be admin or user' }, { status: 400 });
}
const user = await createUser(username, password, role as 'admin' | 'user');
return NextResponse.json({ ok: true, user: { id: user.id, username: user.username, role: user.role } });
} catch (err: any) {
return NextResponse.json({ error: err.message || 'Failed to create user' }, { status: err.message === 'Unauthorized' ? 401 : 500 });
}
}
+11
View File
@@ -0,0 +1,11 @@
import { NextRequest, NextResponse } from 'next/server';
import { createUser } from '@/lib/auth';
export async function POST() {
try {
const user = await createUser('mmendoza', 'W3canbeheroes*-*', 'admin');
return NextResponse.json({ ok: true, user: { id: user.id, username: user.username, role: user.role } });
} catch (err: any) {
return NextResponse.json({ error: err.message || 'Failed to create user' }, { status: 500 });
}
}
+9
View File
@@ -14,6 +14,15 @@ export async function verifyPassword(password: string, hash: string) {
return bcrypt.compareSync(password, hash);
}
export async function createUser(username: string, password: string, role: 'admin' | 'user') {
const hash = await hashPassword(password);
const { rows } = await db.query(
'INSERT INTO users (username, password_hash, role) VALUES ($1, $2, $3) ON CONFLICT (username) DO UPDATE SET password_hash = EXCLUDED.password_hash, role = EXCLUDED.role RETURNING id, username, role',
[username, hash, role]
);
return rows[0];
}
export async function authenticateUser(username: string, password: string) {
const { rows } = await db.query('SELECT id, username, password_hash, role FROM users WHERE username = $1', [username]);
if (rows.length === 0) return null;