From 74b367863ac03c5c8eb92449066f3f34d273367a Mon Sep 17 00:00:00 2001
From: strokh24 <Rokas.Stankunas@Student.Reutlingen-University.DE>
Date: Mon, 14 Oct 2024 23:28:05 +0200
Subject: [PATCH] Implemented basic authorization check

---
 public/js/index.js | 10 ++++++++++
 routes/users.js    | 11 +++++++++++
 2 files changed, 21 insertions(+)

diff --git a/public/js/index.js b/public/js/index.js
index 5d80645..a253202 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 13da3ed..2a5feb7 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) => {
-- 
GitLab