Introduces a GET route for /api/login to redirect to /api/auto-login-admin, and enhances error handling and logging within the local authentication module, particularly for admin user retrieval. Replit-Commit-Author: Agent Replit-Commit-Session-Id: 42d8028a-fa71-4ec2-938c-e43eedf7df01 Replit-Commit-Checkpoint-Type: full_checkpoint Replit-Commit-Screenshot-Url: https://storage.googleapis.com/screenshot-production-us-central1/6d543d2c-20b9-4ea6-93fe-70fe9b1d9f80/42d8028a-fa71-4ec2-938c-e43eedf7df01/EAVbbe1
178 lines
5.6 KiB
TypeScript
178 lines
5.6 KiB
TypeScript
// Sistema autenticazione locale per deployment server esterno (non-Replit)
|
|
import passport from "passport";
|
|
import { Strategy as LocalStrategy } from "passport-local";
|
|
import session from "express-session";
|
|
import type { Express } from "express";
|
|
import connectPg from "connect-pg-simple";
|
|
import { storage } from "./storage";
|
|
// Credenziali admin di default per demo/sviluppo
|
|
const DEFAULT_ADMIN_EMAIL = "admin@vt.alfacom.it";
|
|
const DEFAULT_ADMIN_PASSWORD = "admin123"; // CAMBIARE IN PRODUZIONE!
|
|
const DEFAULT_ADMIN_ID = "local-admin-vt";
|
|
|
|
export function getSession() {
|
|
const sessionTtl = 7 * 24 * 60 * 60 * 1000; // 1 settimana
|
|
const pgStore = connectPg(session);
|
|
const sessionStore = new pgStore({
|
|
conString: process.env.DATABASE_URL,
|
|
createTableIfMissing: false,
|
|
ttl: sessionTtl,
|
|
tableName: "sessions",
|
|
});
|
|
return session({
|
|
secret: process.env.SESSION_SECRET!,
|
|
store: sessionStore,
|
|
resave: false,
|
|
saveUninitialized: false,
|
|
cookie: {
|
|
httpOnly: true,
|
|
secure: process.env.NODE_ENV === 'production',
|
|
maxAge: sessionTtl,
|
|
},
|
|
});
|
|
}
|
|
|
|
async function initDefaultAdmin() {
|
|
try {
|
|
// Verifica se esiste già un admin
|
|
const users = await storage.getAllUsers();
|
|
const adminExists = users.some((u: any) => u.email === DEFAULT_ADMIN_EMAIL);
|
|
|
|
if (!adminExists) {
|
|
// Crea utente admin di default
|
|
await storage.upsertUser({
|
|
id: DEFAULT_ADMIN_ID,
|
|
email: DEFAULT_ADMIN_EMAIL,
|
|
firstName: "Admin",
|
|
lastName: "Sistema",
|
|
profileImageUrl: null,
|
|
});
|
|
|
|
// Imposta ruolo admin
|
|
await storage.updateUserRole(DEFAULT_ADMIN_ID, "admin");
|
|
|
|
console.log(`✅ [LocalAuth] Admin di default creato: ${DEFAULT_ADMIN_EMAIL}`);
|
|
}
|
|
} catch (error) {
|
|
console.error("❌ [LocalAuth] Errore creazione admin:", error);
|
|
}
|
|
}
|
|
|
|
export async function setupLocalAuth(app: Express) {
|
|
app.set("trust proxy", 1);
|
|
app.use(getSession());
|
|
app.use(passport.initialize());
|
|
app.use(passport.session());
|
|
|
|
// Inizializza admin di default
|
|
await initDefaultAdmin();
|
|
|
|
// Strategia passport-local
|
|
passport.use(new LocalStrategy(
|
|
{ usernameField: "email" },
|
|
async (email, password, done) => {
|
|
try {
|
|
// Per demo: accetta credenziali admin di default
|
|
if (email === DEFAULT_ADMIN_EMAIL && password === DEFAULT_ADMIN_PASSWORD) {
|
|
const users = await storage.getAllUsers();
|
|
const admin = users.find((u: any) => u.email === DEFAULT_ADMIN_EMAIL);
|
|
|
|
if (admin) {
|
|
return done(null, { id: admin.id, email: admin.email });
|
|
}
|
|
}
|
|
|
|
// Credenziali non valide
|
|
return done(null, false, { message: "Credenziali non valide" });
|
|
} catch (error) {
|
|
return done(error);
|
|
}
|
|
}
|
|
));
|
|
|
|
passport.serializeUser((user: any, done) => {
|
|
done(null, user.id);
|
|
});
|
|
|
|
passport.deserializeUser(async (id: string, done) => {
|
|
try {
|
|
const users = await storage.getAllUsers();
|
|
const user = users.find((u: any) => u.id === id);
|
|
done(null, user || null);
|
|
} catch (error) {
|
|
done(error);
|
|
}
|
|
});
|
|
|
|
// Route login GET (redirect auto-login per compatibilità)
|
|
app.get("/api/login", (req, res) => {
|
|
// Redirect a auto-login admin per demo
|
|
res.redirect("/api/auto-login-admin");
|
|
});
|
|
|
|
// Route login locale POST
|
|
app.post("/api/local-login", passport.authenticate("local"), (req, res) => {
|
|
res.json({
|
|
success: true,
|
|
user: req.user,
|
|
message: "Login effettuato con successo"
|
|
});
|
|
});
|
|
|
|
// Route auto-login admin (solo per demo/sviluppo)
|
|
app.get("/api/auto-login-admin", async (req, res) => {
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
console.warn("⚠️ [LocalAuth] Auto-login admin attivato (solo sviluppo!)");
|
|
}
|
|
|
|
try {
|
|
console.log("🔍 [LocalAuth] Recupero lista utenti...");
|
|
const users = await storage.getAllUsers();
|
|
console.log(`✅ [LocalAuth] Trovati ${users.length} utenti`);
|
|
|
|
const admin = users.find((u: any) => u.email === DEFAULT_ADMIN_EMAIL);
|
|
|
|
if (admin) {
|
|
console.log(`✅ [LocalAuth] Admin trovato: ${admin.email}`);
|
|
req.login({ id: admin.id, email: admin.email }, (err) => {
|
|
if (err) {
|
|
console.error("❌ [LocalAuth] Errore req.login:", err);
|
|
return res.status(500).json({ error: "Errore auto-login", details: err.message });
|
|
}
|
|
console.log("✅ [LocalAuth] Login effettuato, redirect a /");
|
|
res.redirect("/");
|
|
});
|
|
} else {
|
|
console.error(`❌ [LocalAuth] Admin non trovato (cercato: ${DEFAULT_ADMIN_EMAIL})`);
|
|
res.status(404).json({ error: "Admin non trovato", users: users.map((u: any) => u.email) });
|
|
}
|
|
} catch (error: any) {
|
|
console.error("❌ [LocalAuth] Errore in auto-login-admin:", error);
|
|
res.status(500).json({
|
|
error: "Errore server",
|
|
message: error.message,
|
|
stack: process.env.NODE_ENV === 'development' ? error.stack : undefined
|
|
});
|
|
}
|
|
});
|
|
|
|
// Route logout
|
|
app.get("/api/logout", (req, res) => {
|
|
req.logout(() => {
|
|
res.redirect("/");
|
|
});
|
|
});
|
|
|
|
console.log("✅ [LocalAuth] Sistema autenticazione locale attivato");
|
|
console.log(`📧 Email admin: ${DEFAULT_ADMIN_EMAIL}`);
|
|
console.log(`🔑 Password admin: ${DEFAULT_ADMIN_PASSWORD}`);
|
|
console.log(`🔗 Auto-login: GET /api/auto-login-admin`);
|
|
}
|
|
|
|
export const isAuthenticated = async (req: any, res: any, next: any) => {
|
|
if (!req.isAuthenticated()) {
|
|
return res.status(401).json({ message: "Unauthorized" });
|
|
}
|
|
next();
|
|
};
|