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";
|
|
|
|
|
|
2026-06-09 13:38:58 +02:00
|
|
|
const isProduction = process.env.NODE_ENV === "production";
|
|
|
|
|
|
|
|
|
|
const crossOriginCookieOptions = {
|
|
|
|
|
httpOnly: true,
|
|
|
|
|
sameSite: "none" as const,
|
|
|
|
|
secure: true,
|
|
|
|
|
path: "/",
|
|
|
|
|
};
|
|
|
|
|
|
2026-06-09 13:01:53 +02:00
|
|
|
export const authConfig: ExpressAuthConfig = {
|
2026-06-09 13:38:58 +02:00
|
|
|
basePath: "/api/auth",
|
2026-06-09 13:01:53 +02:00
|
|
|
trustHost: true,
|
|
|
|
|
secret: process.env.AUTH_SECRET,
|
2026-06-09 13:38:58 +02:00
|
|
|
useSecureCookies: isProduction,
|
2026-06-09 13:01:53 +02:00
|
|
|
session: { strategy: "jwt" },
|
|
|
|
|
pages: { signIn: "/login" },
|
2026-06-09 13:38:58 +02:00
|
|
|
cookies: isProduction
|
|
|
|
|
? {
|
|
|
|
|
sessionToken: { options: crossOriginCookieOptions },
|
|
|
|
|
csrfToken: { options: { ...crossOriginCookieOptions, httpOnly: false } },
|
|
|
|
|
callbackUrl: { options: crossOriginCookieOptions },
|
|
|
|
|
}
|
|
|
|
|
: undefined,
|
2026-06-09 13:01:53 +02:00
|
|
|
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;
|
|
|
|
|
},
|
|
|
|
|
},
|
|
|
|
|
};
|