feat: sessão #3 — lib (db/auth/email/validations), API routes, NextAuth v5, middleware, páginas account/shelters/shelter-dashboard, Prisma v7 fix

This commit is contained in:
2026-05-21 09:01:59 +01:00
parent e6ebc0909c
commit e62dc9d6e6
44 changed files with 5341 additions and 273 deletions

View File

@@ -0,0 +1,35 @@
/**
* Validação de +18 anos — sempre executada no servidor.
* Nunca confiar no cliente para esta verificação.
*/
export function isAdult(birthdate: Date): boolean {
const today = new Date();
const age18 = new Date(
birthdate.getFullYear() + 18,
birthdate.getMonth(),
birthdate.getDate()
);
return today >= age18;
}
export function validateAge(birthdateStr: string): {
valid: boolean;
error?: string;
} {
const birthdate = new Date(birthdateStr);
if (isNaN(birthdate.getTime())) {
return { valid: false, error: 'Data de nascimento inválida.' };
}
const now = new Date();
if (birthdate > now) {
return { valid: false, error: 'Data de nascimento não pode ser no futuro.' };
}
if (!isAdult(birthdate)) {
return { valid: false, error: 'Tens de ter pelo menos 18 anos para criar conta.' };
}
return { valid: true };
}

60
lib/auth/config.ts Normal file
View File

@@ -0,0 +1,60 @@
import NextAuth from 'next-auth';
import Credentials from 'next-auth/providers/credentials';
import { prisma } from '@/lib/db/prisma';
import { verifyPassword } from '@/lib/auth/password';
import { loginSchema } from '@/lib/validations/auth';
export const { handlers, auth, signIn, signOut } = NextAuth({
providers: [
Credentials({
name: 'credentials',
credentials: {
email: { label: 'Email', type: 'email' },
password: { label: 'Palavra-passe', type: 'password' },
},
async authorize(credentials) {
const parsed = loginSchema.safeParse(credentials);
if (!parsed.success) return null;
const { email, password } = parsed.data;
const user = await prisma.user.findUnique({ where: { email } });
if (!user) return null;
const valid = await verifyPassword(password, user.password);
if (!valid) return null;
return {
id: user.id,
email: user.email,
name: user.name,
role: user.role,
};
},
}),
],
callbacks: {
async jwt({ token, user }) {
if (user) {
token.id = user.id;
token.role = (user as { role?: string }).role;
}
return token;
},
async session({ session, token }) {
if (token && session.user) {
session.user.id = token.id as string;
(session.user as { role?: string }).role = token.role as string;
}
return session;
},
},
pages: {
signIn: '/auth/login',
error: '/auth/login',
},
session: { strategy: 'jwt' },
});

14
lib/auth/password.ts Normal file
View File

@@ -0,0 +1,14 @@
import bcrypt from 'bcryptjs';
const BCRYPT_ROUNDS = 12;
export async function hashPassword(password: string): Promise<string> {
return bcrypt.hash(password, BCRYPT_ROUNDS);
}
export async function verifyPassword(
password: string,
hash: string
): Promise<boolean> {
return bcrypt.compare(password, hash);
}