refactor(auth): remove debug logging and enhance session middleware

- Eliminated extensive debug logging from the login strategy and verification endpoint to streamline the authentication process.
- Updated session middleware to improve cookie handling, enabling proxy support and adjusting session creation behavior.
- Ensured secure cookie settings for cross-origin requests in production environments.
This commit is contained in:
chamikaJ
2025-06-02 13:20:40 +05:30
parent 24fa837a39
commit 69f5009579
4 changed files with 11 additions and 49 deletions

View File

@@ -35,20 +35,6 @@ export default class AuthController extends WorklenzControllerBase {
const auth_error = errors.length > 0 ? errors[0] : null;
const message = messages.length > 0 ? messages[0] : null;
// Debug logging
console.log("=== VERIFY ENDPOINT HIT ===");
console.log("Verify endpoint - Strategy:", req.query.strategy);
console.log("Verify endpoint - Authenticated:", req.isAuthenticated());
console.log("Verify endpoint - User:", !!req.user);
console.log("Verify endpoint - User ID:", req.user?.id);
console.log("Verify endpoint - Auth error:", auth_error);
console.log("Verify endpoint - Success message:", message);
console.log("Verify endpoint - Flash errors:", errors);
console.log("Verify endpoint - Flash messages:", messages);
console.log("Verify endpoint - Session ID:", req.sessionID);
console.log("Verify endpoint - Session passport:", (req.session as any).passport);
console.log("Verify endpoint - Session flash:", (req.session as any).flash);
// Determine title based on authentication status and strategy
let title = null;
if (req.query.strategy) {

View File

@@ -5,12 +5,15 @@ import { isProduction } from "../shared/utils";
// eslint-disable-next-line @typescript-eslint/no-var-requires
const pgSession = require("connect-pg-simple")(session);
// For cross-origin requests, we need special cookie settings
const isHttps = process.env.NODE_ENV === "production" || process.env.FORCE_HTTPS === "true";
export default session({
name: process.env.SESSION_NAME,
name: process.env.SESSION_NAME || "worklenz.sid",
secret: process.env.SESSION_SECRET || "development-secret-key",
proxy: false,
proxy: true, // Enable proxy support for proper session handling
resave: false,
saveUninitialized: true,
saveUninitialized: false, // Changed to false to prevent unnecessary session creation
rolling: true,
store: new pgSession({
pool: db.pool,
@@ -18,10 +21,10 @@ export default session({
}),
cookie: {
path: "/",
// secure: isProduction(),
// httpOnly: isProduction(),
// sameSite: "none",
// domain: isProduction() ? ".worklenz.com" : undefined,
secure: isHttps, // Only secure in production with HTTPS
httpOnly: true, // Enable httpOnly for security
sameSite: isHttps ? "none" : false, // Use "none" for HTTPS cross-origin, disable for HTTP
domain: undefined, // Don't set domain for cross-origin requests
maxAge: 30 * 24 * 60 * 60 * 1000 // 30 days
}
});

View File

@@ -6,18 +6,11 @@ import { Request } from "express";
import { ERROR_KEY, SUCCESS_KEY } from "./passport-constants";
async function handleLogin(req: Request, email: string, password: string, done: any) {
console.log("=== LOGIN STRATEGY STARTED ===");
console.log("Login attempt for:", email);
console.log("Password provided:", !!password);
console.log("Request body:", req.body);
// Clear any existing flash messages
(req.session as any).flash = {};
if (!email || !password) {
console.log("Missing credentials - email:", !!email, "password:", !!password);
const errorMsg = "Please enter both email and password";
console.log("Setting error flash message:", errorMsg);
req.flash(ERROR_KEY, errorMsg);
return done(null, false);
}
@@ -29,33 +22,25 @@ async function handleLogin(req: Request, email: string, password: string, done:
AND google_id IS NULL
AND is_deleted IS FALSE;`;
const result = await db.query(q, [email]);
console.log("User query result count:", result.rowCount);
const [data] = result.rows;
if (!data?.password) {
console.log("No account found for email:", email);
const errorMsg = "No account found with this email";
console.log("Setting error flash message:", errorMsg);
req.flash(ERROR_KEY, errorMsg);
return done(null, false);
}
const passwordMatch = bcrypt.compareSync(password, data.password);
console.log("Password match result:", passwordMatch);
if (passwordMatch && email === data.email) {
delete data.password;
console.log("Login successful for user:", data.id);
const successMsg = "User successfully logged in";
console.log("Setting success flash message:", successMsg);
req.flash(SUCCESS_KEY, successMsg);
return done(null, data);
}
console.log("Password mismatch or email mismatch");
const errorMsg = "Incorrect email or password";
console.log("Setting error flash message:", errorMsg);
req.flash(ERROR_KEY, errorMsg);
return done(null, false);
} catch (error) {

View File

@@ -17,19 +17,7 @@ const options = (key: string): passport.AuthenticateOptions => ({
successRedirect: `/secure/verify?strategy=${key}`
});
// Debug middleware for login
const loginDebugMiddleware = (req: express.Request, res: express.Response, next: express.NextFunction) => {
console.log("=== LOGIN ROUTE HIT ===");
console.log("Request method:", req.method);
console.log("Request URL:", req.url);
console.log("Request body:", req.body);
console.log("Content-Type:", req.headers["content-type"]);
console.log("Session ID:", req.sessionID);
console.log("Is authenticated before:", req.isAuthenticated());
next();
};
authRouter.post("/login", loginDebugMiddleware, passport.authenticate("local-login", options("login")));
authRouter.post("/login", passport.authenticate("local-login", options("login")));
authRouter.post("/signup", signUpValidator, passwordValidator, passport.authenticate("local-signup", options("signup")));
authRouter.post("/signup/check", signUpValidator, passwordValidator, safeControllerFunction(AuthController.status_check));
authRouter.get("/verify", AuthController.verify);