fix: login/registo funcional — signIn NextAuth, SessionProvider, NEXTAUTH_SECRET real, error handling
This commit is contained in:
@@ -6,51 +6,66 @@ import { validateAge } from '@/lib/auth/age-validation';
|
||||
import { sendEmail, buildWelcomeHtml } from '@/lib/email';
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const body = await request.json();
|
||||
const parsed = registerSchema.safeParse(body);
|
||||
try {
|
||||
const body = await request.json();
|
||||
const parsed = registerSchema.safeParse(body);
|
||||
|
||||
if (!parsed.success) {
|
||||
const errors = parsed.error.flatten().fieldErrors;
|
||||
const firstError = Object.values(errors).flat()[0];
|
||||
return NextResponse.json({ error: firstError ?? 'Dados inválidos.' }, { status: 400 });
|
||||
if (!parsed.success) {
|
||||
const errors = parsed.error.flatten().fieldErrors;
|
||||
const firstError = Object.values(errors).flat()[0];
|
||||
return NextResponse.json({ error: firstError ?? 'Dados inválidos.' }, { status: 400 });
|
||||
}
|
||||
|
||||
const { name, email, password, birthdate, district } = parsed.data;
|
||||
|
||||
// Validação de +18 sempre no servidor
|
||||
const ageCheck = validateAge(birthdate);
|
||||
if (!ageCheck.valid) {
|
||||
return NextResponse.json({ error: ageCheck.error }, { status: 400 });
|
||||
}
|
||||
|
||||
// Verificar se email já existe
|
||||
const existing = await prisma.user.findUnique({ where: { email } });
|
||||
if (existing) {
|
||||
return NextResponse.json({ error: 'Este email já está registado.' }, { status: 409 });
|
||||
}
|
||||
|
||||
const hashedPassword = await hashPassword(password);
|
||||
|
||||
const user = await prisma.user.create({
|
||||
data: {
|
||||
name,
|
||||
email,
|
||||
password: hashedPassword,
|
||||
birthdate: new Date(birthdate),
|
||||
district,
|
||||
},
|
||||
select: { id: true, name: true, email: true },
|
||||
});
|
||||
|
||||
// Email de boas-vindas (não bloqueia a resposta)
|
||||
sendEmail({
|
||||
to: user.email,
|
||||
subject: 'Bem-vindo à PetLink 🐾',
|
||||
html: buildWelcomeHtml({ userName: user.name }),
|
||||
}).catch(console.error);
|
||||
|
||||
return NextResponse.json(
|
||||
{ message: 'Conta criada com sucesso.', userId: user.id },
|
||||
{ status: 201 }
|
||||
);
|
||||
} catch (err: unknown) {
|
||||
console.error('[POST /api/auth/register]', err);
|
||||
|
||||
// Erro de ligação à base de dados — mensagem clara ao utilizador
|
||||
const msg = err instanceof Error ? err.message : '';
|
||||
if (msg.includes('P1001') || msg.includes('connect') || msg.includes('ECONNREFUSED')) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Base de dados temporariamente indisponível. Tenta mais tarde.' },
|
||||
{ status: 503 }
|
||||
);
|
||||
}
|
||||
|
||||
return NextResponse.json({ error: 'Erro interno. Tenta de novo.' }, { status: 500 });
|
||||
}
|
||||
|
||||
const { name, email, password, birthdate, district } = parsed.data;
|
||||
|
||||
// Validação de +18 sempre no servidor
|
||||
const ageCheck = validateAge(birthdate);
|
||||
if (!ageCheck.valid) {
|
||||
return NextResponse.json({ error: ageCheck.error }, { status: 400 });
|
||||
}
|
||||
|
||||
// Verificar se email já existe
|
||||
const existing = await prisma.user.findUnique({ where: { email } });
|
||||
if (existing) {
|
||||
return NextResponse.json({ error: 'Este email já está registado.' }, { status: 409 });
|
||||
}
|
||||
|
||||
const hashedPassword = await hashPassword(password);
|
||||
|
||||
const user = await prisma.user.create({
|
||||
data: {
|
||||
name,
|
||||
email,
|
||||
password: hashedPassword,
|
||||
birthdate: new Date(birthdate),
|
||||
district,
|
||||
},
|
||||
select: { id: true, name: true, email: true },
|
||||
});
|
||||
|
||||
// Email de boas-vindas (não bloqueia)
|
||||
sendEmail({
|
||||
to: user.email,
|
||||
subject: 'Bem-vindo à PetLink 🐾',
|
||||
html: buildWelcomeHtml({ userName: user.name }),
|
||||
}).catch(console.error);
|
||||
|
||||
return NextResponse.json(
|
||||
{ message: 'Conta criada com sucesso.', userId: user.id },
|
||||
{ status: 201 }
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user