I am making a URL shortener. Here is my code for it. I want limit some URLs open only for login users. Why this is not working
app.get('/:shortUrl', async (req, res) => {
try {
const { shortUrl } = req.params;
const urlData = await URL.findOne({ shortUrl });
if (urlData) {
const currentDate = new Date();
const startDate = urlData.startDate ? new Date(urlData.startDate) : null;
const expirationDate = urlData.expirationDate ? new Date(urlData.expirationDate) : null;
const requireSignIn = urlData.requireSignIn || false;
console.log('requireSignIn', requireSignIn);
console.log('req.session.isLogged', req.session.isLogged);
if (requireSignIn && req.session.isLogged === undefined) {
return res.status(401).send('Please login to access this URL');
}
if (startDate === null && expirationDate === null) {
// No start date and no expiration date, URL is accessible
res.redirect(urlData.originalUrl);
} else if (startDate !== null && startDate > currentDate) {
// Start date is in the future, URL is not yet available
res.status(400).send('Shortened URL is not available yet');
} else if (expirationDate !== null && expirationDate < currentDate) {
// Expiration date is in the past, URL has expired
res.status(400).send('Shortened URL has expired');
} else {
// URL is accessible
res.redirect(urlData.originalUrl);
}
} else {
res.status(404).send('URL not found');
}
} catch (error) {
console.error('Error redirecting:', error);
res.status(500).send('Internal Server Error');
}
});
this is how I save it on my login API
app.post('/api/logout', (req, res) => {
// Clear isLogged from the session upon logout
req.session.isLogged = false;
req.logout(); // Optional: If you are using passport, you can also call req.logout() to remove the user from the session
res.status(200).json({ message: 'Logout successful' });
});
I'm facing an issue where even after logging in, the application still prompts users to log in to access URLs marked as requiring sign-in. Can someone help me identify the problem and suggest a solution? Thank you!
THis is the log message
requireSignIn true
req.session.isLogged undefined