diff --git a/public/js/index.js b/public/js/index.js index 5d8064574ffe7b926ddbcceae836114e138a021f..a2532025fac685cc0ace84eb709674bcada54592 100644 --- a/public/js/index.js +++ b/public/js/index.js @@ -1,4 +1,14 @@ document.addEventListener('DOMContentLoaded', async () => { + // Event for checking if the user is logged in + try { + const res = await fetch('/api/users/loggedin', { method: 'POST' }); + if (!res.ok) { + window.location.href = 'login.html'; + } + } catch (err) { + console.error('Error while checking if a user is logged in:', err); + } + const logoutBtn = document.getElementById('logout-btn'); // Event for the logout button diff --git a/routes/users.js b/routes/users.js index 13da3ede5d57415fd6a474d353b623482b5b0a2a..2a5feb7bc706c6995e34fdba2847b99c503fdf68 100644 --- a/routes/users.js +++ b/routes/users.js @@ -58,6 +58,17 @@ router.post('/login', async (req, res) => { } }); +// Checking if the user is logged in +router.post('/loggedin', (req, res) => { + try { + if (!req.session.user) { + res.status(403).json({ error: 'Unauthorized' }); + } + } catch (error) { + console.error('Authorization check failed:', error); + res.status(500).json({ error: 'Server error' }); + } +}); // Closing user session router.post('/logout', (req, res) => {