From 4f5b073a1d9ea99a04b66666fddac549d9930e42 Mon Sep 17 00:00:00 2001 From: ethanf Date: Thu, 14 Aug 2025 14:36:29 -0500 Subject: [PATCH] fix: improve session handling and authentication checks --- server/server.js | 46 ++++++++++++++++++++++++++++++++---------- src/hooks/useAuth.ts | 48 +++++++++++++++++++++++++++----------------- 2 files changed, 65 insertions(+), 29 deletions(-) diff --git a/server/server.js b/server/server.js index ceb1b29..fd23aea 100644 --- a/server/server.js +++ b/server/server.js @@ -52,16 +52,17 @@ app.use(cors({ app.use(express.json()); app.use(session({ secret: process.env.SESSION_SECRET || 'your-secret-key-change-this', - resave: false, + resave: true, saveUninitialized: false, + rolling: true, cookie: { - secure: process.env.NODE_ENV === 'production', // HTTPS in production - maxAge: 24 * 60 * 60 * 1000, + secure: process.env.NODE_ENV === 'production', + maxAge: 24 * 60 * 60 * 1000, // 24 hours httpOnly: true, - sameSite: process.env.NODE_ENV === 'production' ? 'lax' : 'lax', // Important for cross-site cookies + sameSite: process.env.NODE_ENV === 'production' ? 'lax' : 'lax', domain: process.env.NODE_ENV === 'production' ? '.ethanf.gg' : undefined }, - name: 's22poll.sid' // Custom session name + name: 's22poll.sid' })); app.use(passport.initialize()); @@ -105,12 +106,28 @@ passport.deserializeUser((user, done) => { app.get('/auth/steam', passport.authenticate('steam')); app.get('/auth/steam/return', - passport.authenticate('steam', { failureRedirect: `${FRONTEND_URL}` }), + passport.authenticate('steam', { failureRedirect: '/' }), (req, res) => { - console.log('Steam authentication callback received'); - console.log('User authenticated:', req.user?.displayName); - // Successful authentication, redirect to frontend - res.redirect('/?auth=success'); + console.log('=== Steam Auth Callback ==='); + console.log('Session ID after auth:', req.sessionID); + console.log('User after auth:', req.user); + console.log('Is authenticated after auth:', req.isAuthenticated()); + + // Force session save before redirect + req.session.save((err) => { + if (err) { + console.error('Session save error:', err); + return res.redirect('/?auth=error'); + } + + console.log('Session saved successfully'); + console.log('Session after save:', req.session); + + // Redirect to frontend with a small delay to ensure session is saved + setTimeout(() => { + res.redirect('/?auth=success'); + }, 100); + }); } ); @@ -124,10 +141,17 @@ app.get('/auth/logout', (req, res) => { }); app.get('/auth/user', (req, res) => { + console.log('=== /auth/user endpoint ==='); + console.log('Session ID:', req.sessionID); + console.log('Session:', req.session); + console.log('User:', req.user); + console.log('Is authenticated:', req.isAuthenticated()); + console.log('========================'); + if (req.isAuthenticated()) { res.json({ user: req.user }); } else { - res.status(401).json({ error: 'Not authenticated' }); + res.json({ user: null }); } }); diff --git a/src/hooks/useAuth.ts b/src/hooks/useAuth.ts index 172c464..e76f191 100644 --- a/src/hooks/useAuth.ts +++ b/src/hooks/useAuth.ts @@ -6,37 +6,49 @@ export const useAuth = () => { const [user, setUser] = useState(null); const [loading, setLoading] = useState(true); - useEffect(() => { - const checkAuthStatus = async () => { - try { - console.log('Checking authentication status...'); - const response = await authService.getCurrentUser(); - console.log('Auth check response:', response); + const checkAuthStatus = async () => { + try { + console.log('Checking authentication status...'); + const response = await authService.getCurrentUser(); + console.log('Auth check response:', response); + + if (response.user) { setUser(response.user); - } catch (error) { - console.log('User not authenticated:', error); + console.log('User set successfully:', response.user); + } else { setUser(null); - } finally { - setLoading(false); + console.log('No user found in response'); } - }; + } catch (error) { + console.log('User not authenticated:', error); + setUser(null); + } finally { + setLoading(false); + } + }; - checkAuthStatus(); - - // Check for auth success parameter + useEffect(() => { + // Check for auth success parameter first const urlParams = new URLSearchParams(window.location.search); if (urlParams.get('auth') === 'success') { - console.log('Auth success detected, rechecking user status...'); + console.log('Auth success detected, waiting before checking user status...'); // Remove the auth parameter from URL window.history.replaceState({}, document.title, window.location.pathname); - // Recheck auth status - setTimeout(checkAuthStatus, 1000); + + // Wait a bit longer for session to be fully established + setTimeout(() => { + checkAuthStatus(); + }, 2000); // Increased delay to 2 seconds + } else { + checkAuthStatus(); } }, []); const handleLogin = () => { console.log('Initiating login...'); - window.location.href = `${import.meta.env.PROD ? 'https://s22.ethanf.gg' : 'http://localhost:3001'}/auth/steam`; + const loginUrl = `${import.meta.env.PROD ? 'https://s22.ethanf.gg' : 'http://localhost:3001'}/auth/steam`; + console.log('Login URL:', loginUrl); + window.location.href = loginUrl; }; const handleLogout = async () => {