provapraticabackend/src/auth/config.ts
AV77web 8f6d7e68d8
All checks were successful
Deploy to VPS / build (push) Successful in 17s
Deploy to VPS / deploy (push) Successful in 21s
correzione a Auth/config
2026-06-09 14:15:05 +02:00

80 lines
2.3 KiB
TypeScript

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";
const isProduction = process.env.NODE_ENV === "production";
const crossOriginCookieOptions = {
httpOnly: true,
sameSite: "none" as const,
secure: true,
path: "/",
};
export const authConfig: ExpressAuthConfig = {
basePath: "/api/auth",
trustHost: true,
secret: process.env.AUTH_SECRET,
useSecureCookies: isProduction,
session: { strategy: "jwt" },
// Il frontend gestisce login/registrazione: niente redirect verso pagine backend
pages: { signIn: "/api/auth/error" },
cookies: isProduction
? {
sessionToken: { options: crossOriginCookieOptions },
csrfToken: { options: { ...crossOriginCookieOptions, httpOnly: false } },
callbackUrl: { options: crossOriginCookieOptions },
}
: undefined,
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;
},
},
};