61 lines
1.6 KiB
TypeScript
61 lines
1.6 KiB
TypeScript
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' },
|
|
});
|