Update src/app/api/auth/register/route.ts

This commit is contained in:
2026-03-11 20:53:10 +00:00
parent f0dfa51511
commit e6239e490f

View File

@@ -1,7 +1,11 @@
import { NextRequest, NextResponse } from 'next/server';
import { NextRequest, NextResponse } from "next/server";
import bcrypt from "bcryptjs";
import jwt from "jsonwebtoken";
// Temporary in-memory user storage (replace with database)
const users: Map<string, any> = new Map();
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 {
@@ -10,68 +14,54 @@ export async function POST(request: NextRequest) {
// Validation
if (!name || !email || !password) {
return NextResponse.json(
{ message: 'Name, email, and password are required' },
{ message: "Nome, email e senha são obrigatórios" },
{ status: 400 }
);
}
if (password.length < 6) {
if (password.length < 8) {
return NextResponse.json(
{ message: 'Password must be at least 6 characters' },
{ message: "A senha deve ter pelo menos 8 caracteres" },
{ status: 400 }
);
}
// Check if user already exists
if (users.has(email)) {
const existingUser = users.find((u) => u.email === email);
if (existingUser) {
return NextResponse.json(
{ message: 'User already exists' },
{ message: "Este email já está registrado" },
{ status: 409 }
);
}
// Hash password using simple hash (not production-ready)
const hashedPassword = await hashPassword(password);
// Hash password
const passwordHash = await bcrypt.hash(password, 10);
// Create user
const user = {
id: Math.random().toString(36).substr(2, 9),
name,
email,
password: hashedPassword,
createdAt: new Date(),
};
const userId = `user_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
const newUser = { id: userId, name, email, passwordHash };
users.push(newUser);
users.set(email, user);
// Create JWT-like token (simplified)
const token = Buffer.from(JSON.stringify({ userId: user.id, email })).toString('base64');
// Create JWT token
const token = jwt.sign(
{ id: userId, email, name },
JWT_SECRET,
{ expiresIn: "7d" }
);
return NextResponse.json(
{
message: 'User registered successfully',
token,
user: {
id: user.id,
name: user.name,
email: user.email,
},
user: { id: userId, name, email },
},
{ status: 201 }
);
} catch (error) {
console.error("Register error:", error);
return NextResponse.json(
{ message: 'Registration failed' },
{ message: "Erro ao registrar usuário" },
{ status: 500 }
);
}
}
// Simple hash function (not secure - for development only)
async function hashPassword(password: string): Promise<string> {
const encoder = new TextEncoder();
const data = encoder.encode(password);
const hashBuffer = await crypto.subtle.digest('SHA-256', data);
const hashArray = Array.from(new Uint8Array(hashBuffer));
return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
}
}