feat(auth): add POST /api/auth/register endpoint (task 4.1)

Validates email presence and password length (8+ chars), checks email
uniqueness with 409 on conflict, hashes password with bcryptjs (cost 12),
inserts user into the users table and returns 201 with id/email/name.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Marko Djordjevic 2026-02-20 10:14:55 +01:00
parent 45b6366861
commit 9a5e325632
2 changed files with 65 additions and 1 deletions

View file

@ -0,0 +1,64 @@
import { NextRequest, NextResponse } from 'next/server';
import bcryptjs from 'bcryptjs';
import { eq } from 'drizzle-orm';
import { db } from '@/lib/db';
import { users } from '@/lib/db/schema';
export async function POST(request: NextRequest) {
let body: unknown;
try {
body = await request.json();
} catch {
return NextResponse.json({ error: 'Invalid JSON body' }, { status: 400 });
}
const { email, password, name } = body as Record<string, unknown>;
// Validate email
if (!email || typeof email !== 'string' || email.trim() === '') {
return NextResponse.json({ error: 'Email is required' }, { status: 400 });
}
// Validate password
if (!password || typeof password !== 'string' || password.length < 8) {
return NextResponse.json(
{ error: 'Password must be at least 8 characters' },
{ status: 400 }
);
}
const normalizedEmail = email.trim().toLowerCase();
// Check email uniqueness
const [existingUser] = await db
.select({ id: users.id })
.from(users)
.where(eq(users.email, normalizedEmail))
.limit(1);
if (existingUser) {
return NextResponse.json(
{ error: 'An account with this email already exists' },
{ status: 409 }
);
}
// Hash password
const password_hash = await bcryptjs.hash(password, 12);
// Insert user
const [newUser] = await db
.insert(users)
.values({
email: normalizedEmail,
password_hash,
name: typeof name === 'string' && name.trim() !== '' ? name.trim() : null,
provider: 'credentials',
})
.returning({ id: users.id, email: users.email, name: users.name });
return NextResponse.json(
{ id: newUser.id, email: newUser.email, name: newUser.name },
{ status: 201 }
);
}