Files
bd539cad-e5a1-45ab-8774-c07…/src/app/api/auth/register/route.ts

67 lines
1.8 KiB
TypeScript

import { NextRequest, NextResponse } from "next/server";
import bcrypt from "bcryptjs";
import jwt from "jsonwebtoken";
const JWT_SECRET = process.env.JWT_SECRET || "your-secret-key-change-in-production";
// Mock database - in production, use a real database
const users: Array<{ id: string; name: string; email: string; passwordHash: string }> = [];
export async function POST(request: NextRequest) {
try {
const { name, email, password } = await request.json();
// Validation
if (!name || !email || !password) {
return NextResponse.json(
{ message: "Nome, email e senha são obrigatórios" },
{ status: 400 }
);
}
if (password.length < 8) {
return NextResponse.json(
{ message: "A senha deve ter pelo menos 8 caracteres" },
{ status: 400 }
);
}
// Check if user already exists
const existingUser = users.find((u) => u.email === email);
if (existingUser) {
return NextResponse.json(
{ message: "Este email já está registrado" },
{ status: 409 }
);
}
// Hash password
const passwordHash = await bcrypt.hash(password, 10);
// Create user
const userId = `user_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
const newUser = { id: userId, name, email, passwordHash };
users.push(newUser);
// Create JWT token
const token = jwt.sign(
{ id: userId, email, name },
JWT_SECRET,
{ expiresIn: "7d" }
);
return NextResponse.json(
{
token,
user: { id: userId, name, email },
},
{ status: 201 }
);
} catch (error) {
console.error("Register error:", error);
return NextResponse.json(
{ message: "Erro ao registrar usuário" },
{ status: 500 }
);
}
}