initial version of the app
This commit is contained in:
@@ -0,0 +1,70 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { db } from '@/lib/db';
|
||||
import { users } from '@/lib/db/schema';
|
||||
import { eq } from 'drizzle-orm';
|
||||
import bcrypt from 'bcryptjs';
|
||||
import { createSession } from '@/lib/session';
|
||||
import { z } from 'zod';
|
||||
|
||||
const registerSchema = z.object({
|
||||
email: z.string().email(),
|
||||
name: z.string().min(1),
|
||||
surname: z.string().min(1),
|
||||
password: z.string().min(6),
|
||||
});
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const body = await request.json();
|
||||
const validatedData = registerSchema.parse(body);
|
||||
|
||||
// Check if user already exists
|
||||
const existingUser = await db.select().from(users).where(eq(users.email, validatedData.email)).limit(1);
|
||||
if (existingUser.length > 0) {
|
||||
return NextResponse.json({ error: 'User with this email already exists' }, { status: 400 });
|
||||
}
|
||||
|
||||
// Hash password
|
||||
const hashedPassword = await bcrypt.hash(validatedData.password, 10);
|
||||
|
||||
// Create new user
|
||||
const [newUser] = await db
|
||||
.insert(users)
|
||||
.values({
|
||||
id: crypto.randomUUID(),
|
||||
email: validatedData.email,
|
||||
name: validatedData.name,
|
||||
surname: validatedData.surname,
|
||||
password: hashedPassword,
|
||||
role: 'user',
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
})
|
||||
.returning();
|
||||
|
||||
// Create session
|
||||
await createSession({
|
||||
userId: newUser.id,
|
||||
email: newUser.email,
|
||||
role: newUser.role as 'user' | 'admin',
|
||||
});
|
||||
|
||||
return NextResponse.json({
|
||||
user: {
|
||||
id: newUser.id,
|
||||
email: newUser.email,
|
||||
name: newUser.name,
|
||||
surname: newUser.surname,
|
||||
role: newUser.role,
|
||||
},
|
||||
message: 'User created successfully',
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof z.ZodError) {
|
||||
return NextResponse.json({ error: 'Invalid input data', details: error.errors }, { status: 400 });
|
||||
}
|
||||
|
||||
console.error('Registration error:', error);
|
||||
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user