diff --git a/public/index.html b/public/index.html index ca170f1c94da69385f6698bfa665cb123e73c96c..97a91fcdae16c5915876c18c9f3a4e362e7e6cf3 100644 --- a/public/index.html +++ b/public/index.html @@ -6,6 +6,7 @@ <title>ToDo</title> <link rel="stylesheet" href="./css/index.css" /> <script src="./js/index.js" defer></script> + <script src="./js/authorization.js" defer></script> </head> <body> <div class="container"> diff --git a/public/js/app.js b/public/js/app.js index e76b1042dcc3e03f55e57e2bf9d7d4f958a95566..c5cdc88350aa239f4a0dcc8421a8993e2168fc8c 100644 --- a/public/js/app.js +++ b/public/js/app.js @@ -1,4 +1,4 @@ -// Obtener referencia a los elementos del DOM +// Get reference to DOM elements const taskList = document.querySelector('.task-list ul'); const newTaskForm = document.querySelector('form'); diff --git a/public/js/authorization.js b/public/js/authorization.js new file mode 100644 index 0000000000000000000000000000000000000000..61df3f53043e7b854df6632cbaf1e7907316854b --- /dev/null +++ b/public/js/authorization.js @@ -0,0 +1,11 @@ +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); + } +}); \ No newline at end of file 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) => {