refactor(auth): remove debug logging from authentication methods

- Eliminated console logs from the `verify` and `googleMobileAuthPassport` methods to streamline the code and reduce noise in the logs.
- Updated session middleware to enhance cookie handling for mobile applications, ensuring proper session management without excessive logging.
- Improved session cookie configuration for production and development environments, maintaining compatibility with mobile app requirements.
This commit is contained in:
Chamika J
2025-08-06 12:37:29 +05:30
parent 66edec201f
commit a1aaf9bd59
2 changed files with 8 additions and 111 deletions

View File

@@ -30,14 +30,6 @@ export default class AuthController extends WorklenzControllerBase {
}
public static verify(req: IWorkLenzRequest, res: IWorkLenzResponse) {
console.log("=== VERIFY ENDPOINT DEBUG ===");
console.log("Session ID:", req.sessionID);
console.log("Session data:", req.session);
console.log("Is authenticated:", req.isAuthenticated());
console.log("User in session:", req.user);
console.log("Headers:", req.headers);
console.log("Cookies:", req.cookies);
// Flash messages sent from passport-local-signup.ts and passport-local-login.ts
const errors = req.flash()["error"] || [];
const messages = req.flash()["success"] || [];
@@ -61,14 +53,6 @@ export default class AuthController extends WorklenzControllerBase {
if (req.user)
req.user.build_v = FileConstants.getRelease();
console.log("=== VERIFY RESPONSE ===");
console.log("Title:", title);
console.log("Authenticated:", req.isAuthenticated());
console.log("User:", req.user || null);
console.log("Auth error:", auth_error);
console.log("Message:", message);
console.log("======================");
return res.status(200).send(new AuthResponse(title, req.isAuthenticated(), req.user || null, auth_error, message));
}
@@ -201,11 +185,6 @@ export default class AuthController extends WorklenzControllerBase {
}
public static googleMobileAuthPassport(req: IWorkLenzRequest, res: IWorkLenzResponse, next: NextFunction) {
console.log("=== GOOGLE MOBILE AUTH START ===");
console.log("Session ID before auth:", req.sessionID);
console.log("Session data before auth:", req.session);
console.log("Headers:", req.headers);
console.log("Body:", req.body);
const mobileOptions = {
session: true,
@@ -214,13 +193,7 @@ export default class AuthController extends WorklenzControllerBase {
};
passport.authenticate("google-mobile", mobileOptions, (err: any, user: any, info: any) => {
console.log("=== PASSPORT AUTHENTICATE CALLBACK ===");
console.log("Error:", err);
console.log("User:", user);
console.log("Info:", info);
if (err) {
console.log("Authentication error:", err);
return res.status(500).send({
done: false,
message: "Authentication failed",
@@ -229,19 +202,15 @@ export default class AuthController extends WorklenzControllerBase {
}
if (!user) {
console.log("No user found, info:", info);
return res.status(400).send({
done: false,
message: info?.message || "Authentication failed",
body: null
});
}
console.log("User found, attempting login...");
// Log the user in (create session)
req.login(user, (loginErr) => {
if (loginErr) {
console.log("Login error:", loginErr);
return res.status(500).send({
done: false,
message: "Session creation failed",
@@ -249,26 +218,12 @@ export default class AuthController extends WorklenzControllerBase {
});
}
// Use existing session without regeneration for mobile app compatibility
// Note: This reduces security slightly but ensures session continuity for mobile
console.log("Using existing session ID:", req.sessionID);
console.log("=== LOGIN SUCCESSFUL ===");
console.log("Session ID after login:", req.sessionID);
console.log("Session data after login:", req.session);
console.log("Is authenticated:", req.isAuthenticated());
console.log("User in session:", req.user);
// Add build version
user.build_v = FileConstants.getRelease();
console.log("Sending response...");
console.log("Response headers before send:", res.getHeaders());
// Ensure session is saved and cookie is set
req.session.save((saveErr) => {
if (saveErr) {
console.log("Session save error:", saveErr);
return res.status(500).send({
done: false,
message: "Session save failed",
@@ -279,32 +234,7 @@ export default class AuthController extends WorklenzControllerBase {
// Get session cookie details
const sessionName = process.env.SESSION_NAME || 'connect.sid';
console.log("Session saved successfully");
console.log("Session name:", sessionName);
console.log("Session ID to be sent:", req.sessionID);
// Check if Set-Cookie header is being sent
console.log("Response headers after save:", res.getHeaders());
console.log("Set-Cookie header:", res.getHeader('set-cookie'));
// Manually set the session cookie since automatic setting isn't working
if (!res.getHeader('set-cookie')) {
console.log("Set-Cookie header not found, manually setting cookie...");
// Force the session middleware to set the cookie by marking the session as modified
req.session.touch();
// Wait a bit for the middleware to process
setTimeout(() => {
const finalCookieHeader = res.getHeader('set-cookie');
console.log("Cookie header after touch:", finalCookieHeader);
}, 10);
console.log("Session touched to force cookie setting");
}
// Return response with session info for mobile app to handle
// Include the session ID in both cookie and header for maximum compatibility
res.setHeader('X-Session-ID', req.sessionID);
res.setHeader('X-Session-Name', sessionName);
@@ -313,9 +243,7 @@ export default class AuthController extends WorklenzControllerBase {
message: "Login successful",
user,
authenticated: true,
sessionId: req.sessionID, // Mobile app should use this session ID
sessionCookie: sessionName, // Cookie name for mobile app
// Additional fields for mobile app cookie handling
sessionId: req.sessionID,
sessionName: sessionName,
newSessionId: req.sessionID
});

View File

@@ -21,9 +21,10 @@ const sessionConfig = {
cookie: {
path: "/",
httpOnly: true,
// For mobile app support, we might need these settings:
// For mobile app support in production, use "none", for local development use "lax"
sameSite: isProduction() ? "none" as const : "lax" as const,
secure: isProduction(), // Required when sameSite is "none"
// Secure only in production (HTTPS required for sameSite: "none")
secure: isProduction(),
domain: isProduction() ? ".worklenz.com" : undefined,
maxAge: 30 * 24 * 60 * 60 * 1000 // 30 days
},
@@ -33,11 +34,6 @@ const sessionConfig = {
}
};
console.log("Session configuration:", {
...sessionConfig,
secret: "[REDACTED]"
});
const sessionMiddleware = session(sessionConfig);
// Enhanced session middleware that supports both cookies and headers for mobile apps
@@ -46,29 +42,16 @@ export default (req: any, res: any, next: any) => {
const headerSessionId = req.headers["x-session-id"];
const headerSessionName = req.headers["x-session-name"];
console.log("Session middleware debug:");
console.log("- Cookie header:", req.headers.cookie);
console.log("- X-Session-ID header:", headerSessionId);
console.log("- X-Session-Name header:", headerSessionName);
// Only process headers if they exist AND there's no existing valid session cookie
if (headerSessionId && headerSessionName) {
console.log("Mobile app using header-based session:", headerSessionId);
// The problem is cookie signature - we need to create a properly signed cookie
const secret = process.env.SESSION_SECRET || "development-secret-key";
try {
// Create a signed cookie using the session secret
const signedSessionId = `s:${ cookieSignature.sign(headerSessionId, secret)}`;
const signedSessionId = `s:${cookieSignature.sign(headerSessionId, secret)}`;
const encodedSignedId = encodeURIComponent(signedSessionId);
const sessionCookie = `${headerSessionName}=${encodedSignedId}`;
console.log("Creating signed session cookie:");
console.log("- Raw session ID:", headerSessionId);
console.log("- Signed session ID:", signedSessionId);
console.log("- Encoded signed ID:", encodedSignedId);
console.log("- Final cookie:", sessionCookie);
if (req.headers.cookie) {
// Replace existing session cookie while keeping other cookies
req.headers.cookie = req.headers.cookie
@@ -80,27 +63,13 @@ export default (req: any, res: any, next: any) => {
// Set the session cookie from header
req.headers.cookie = sessionCookie;
}
console.log("Updated cookie header:", req.headers.cookie);
} catch (error) {
console.log("Error creating signed cookie:", error);
// Fallback to the old method
const sessionCookie = `${headerSessionName}=s%3A${headerSessionId}`;
req.headers.cookie = sessionCookie;
}
}
sessionMiddleware(req, res, (err: any) => {
if (err) {
console.log("Session middleware error:", err);
}
// Debug what the session middleware produced
console.log("After session middleware:");
console.log("- Session ID:", (req as any).sessionID);
console.log("- Session data exists:", !!(req as any).session);
console.log("- Session passport data:", (req as any).session?.passport);
console.log("- Is authenticated:", !!(req as any).isAuthenticated && (req as any).isAuthenticated());
next(err);
});
// Always call the original session middleware (handles both cookie and header-converted cases)
sessionMiddleware(req, res, next);
};