provapraticabackend/src/auth/config.ts

62 lines
1.8 KiB
TypeScript
Raw Normal View History

2026-06-09 13:01:53 +02:00
import type { ExpressAuthConfig } from "@auth/express";
import Credentials from "@auth/express/providers/credentials";
import bcrypt from "bcryptjs";
import type { RowDataPacket } from "mysql2";
import pool from "../db/pool.js";
import type { Ruolo, Utente } from "../types/index.js";
export const authConfig: ExpressAuthConfig = {
trustHost: true,
secret: process.env.AUTH_SECRET,
session: { strategy: "jwt" },
pages: { signIn: "/login" },
providers: [
Credentials({
credentials: {
email: { label: "Email", type: "email" },
password: { label: "Password", type: "password" },
},
async authorize(credentials) {
const email = credentials?.email?.toString().trim().toLowerCase();
const password = credentials?.password?.toString();
if (!email || !password) return null;
const [rows] = await pool.execute<RowDataPacket[]>(
"SELECT utente_id, nome, cognome, email, password_hash, ruolo FROM utenti WHERE email = ?",
[email]
);
const user = rows[0] as Utente | undefined;
if (!user) return null;
const valid = await bcrypt.compare(password, user.password_hash);
if (!valid) return null;
return {
id: String(user.utente_id),
email: user.email,
name: `${user.nome} ${user.cognome}`,
ruolo: user.ruolo as Ruolo,
};
},
}),
],
callbacks: {
async jwt({ token, user }) {
if (user) {
token.id = user.id;
token.ruolo = user.ruolo;
}
return token;
},
async session({ session, token }) {
if (session.user) {
session.user.id = token.id as string;
session.user.ruolo = token.ruolo as Ruolo;
}
return session;
},
},
};