fix: improve session handling and authentication checks

This commit is contained in:
ethanf 2025-08-14 14:36:29 -05:00
parent 6fb68fded9
commit 4f5b073a1d
2 changed files with 65 additions and 29 deletions

View File

@ -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
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 });
}
});

View File

@ -6,13 +6,19 @@ export const useAuth = () => {
const [user, setUser] = useState<SteamUser | null>(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);
if (response.user) {
setUser(response.user);
console.log('User set successfully:', response.user);
} else {
setUser(null);
console.log('No user found in response');
}
} catch (error) {
console.log('User not authenticated:', error);
setUser(null);
@ -21,22 +27,28 @@ export const useAuth = () => {
}
};
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 () => {