Repository: kalviumcommunity/S_84_SnackSlam
Pull request #28: Added auth check cookie for login
Author: login: kartikay-28
Labels: name: Review effort 3/5
Created: 2025-04-03T04:20:33Z | Merged: 2025-04-03T04:22:08Z

### **PR Type**
Enhancement, Bug fix


___

### **Description**
- Added authentication routes for login, logout, and auth check.

- Integrated cookie-based authentication in the frontend.

- Enhanced server structure with improved route organization.

- Updated dependencies to include `cookie-parser`.


___



### **Changes walkthrough** 📝
<table><thead><tr><th></th><th align="left">Relevant files</th></tr></thead><tbody><tr><td><strong>Enhancement</strong></td><td><table>
<tr>
  <td>
    <details>
      <summary><strong>auth.js</strong><dd><code>Added authentication routes for login and logout</code>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </dd></summary>
<hr>

Backend/routes/auth.js

<li>Added authentication routes for login, logout, and auth check.<br> <li> Implemented cookie-based authentication for login.<br> <li> Added error handling for invalid usernames and server errors.


</details>


  </td>
  <td><a href="https://github.com/kalviumcommunity/S_84_SnackSlam/pull/28/files#diff-f88821281eb8c7054e20c1280d0d498ec636028245285c0d47e227938bc62e32">+31/-0</a>&nbsp; &nbsp; </td>

</tr>

<tr>
  <td>
    <details>
      <summary><strong>server.js</strong><dd><code>Integrated authentication routes and improved server structure</code></dd></summary>
<hr>

Backend/server.js

<li>Integrated <code>authRoutes</code> for authentication endpoints.<br> <li> Improved server logs for MongoDB connection.<br> <li> Enhanced API route structure for better organization.


</details>


  </td>
  <td><a href="https://github.com/kalviumcommunity/S_84_SnackSlam/pull/28/files#diff-6ccbaf6041c44c73c4e29f8c1ea8cf0e4059302f9d086525e63773bf00115f4a">+24/-21</a>&nbsp; </td>

</tr>

<tr>
  <td>
    <details>
      <summary><strong>LandingPage.jsx</strong><dd><code>Integrated authentication in LandingPage with API</code>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </dd></summary>
<hr>

Frontend/client/src/pages/LandingPage.jsx

<li>Integrated login and logout functionality with API.<br> <li> Added cookie-based authentication check on page load.<br> <li> Improved login button validation for empty usernames.<br> <li> Enhanced logout functionality with error handling.


</details>


  </td>
  <td><a href="https://github.com/kalviumcommunity/S_84_SnackSlam/pull/28/files#diff-9b857c8b68b98bd12bb0c287d2547561526eb3b3a38d9dac7f443b3cf7b44001">+44/-18</a>&nbsp; </td>

</tr>
</table></td></tr><tr><td><strong>Dependencies</strong></td><td><table>
<tr>
  <td>
    <details>
      <summary><strong>package.json</strong><dd><code>Added `cookie-parser` dependency</code>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </dd></summary>
<hr>

Backend/package.json

- Added `cookie-parser` dependency for handling cookies.


</details>


  </td>
  <td><a href="https://github.com/kalviumcommunity/S_84_SnackSlam/pull/28/files#diff-778446475f8ccae7e22b6fef6295206a3a0d7524dfa99600af66098b0deeae85">+1/-0</a>&nbsp; &nbsp; &nbsp; </td>

</tr>
</table></td></tr></tr></tbody></table>

___

> <details> <summary>  Need help?</summary><li>Type <code>/help how to ...</code> in the comments thread for any questions about Qodo Merge usage.</li><li>Check out the <a href="https://qodo-merge-docs.qodo.ai/usage-guide/">documentation</a> for more information.</li></details>


Diff:
diff --git a/Backend/package.json b/Backend/package.json
index b6cfab9..4381570 100644
--- a/Backend/package.json
+++ b/Backend/package.json
@@ -12,6 +12,7 @@
   "license": "ISC",
   "description": "",
   "dependencies": {
+    "cookie-parser": "^1.4.7",
     "cors": "^2.8.5",
     "dotenv": "^16.4.7",
     "express": "^4.21.2",
diff --git a/Backend/routes/auth.js b/Backend/routes/auth.js
new file mode 100644
index 0000000..c67535b
--- /dev/null
+++ b/Backend/routes/auth.js
@@ -0,0 +1,31 @@
+const express = require("express");
+const router = express.Router();
+
+// Dummy user data (in real projects, use a database)
+const users = ["John", "Alice", "Bob","Kartikay","Diven","Aryaman","Akshit","Thakoor","Rishi","Chris","Krish"];
+
+router.post("/login", (req, res) => {
+    const { username } = req.body;
+    if (!username || !users.includes(username)) {
+        return res.status(401).json({ message: "Invalid username" });
+    }
+    res.cookie("username", username, { httpOnly: true, sameSite: "Strict" });
+    res.json({ message: "Login successful", username });
+});
+
+router.post("/logout", (req, res) => {
+    res.clearCookie("username");
+    res.json({ message: "Logged out successfully" });
+});
+
+router.get('/check-auth', async (req, res) => {
+    try {
+      res.json({ isAuthenticated: true, user: req.user });
+    } catch (error) {
+      console.error('Check Auth Error:', error);
+      res.status(500).json({ message: 'Internal Server Error' });
+    }
+  });
+  
+
+module.exports = router;
diff --git a/Backend/server.js b/Backend/server.js
index 1e27cd0..8d476f1 100644
--- a/Backend/server.js
+++ b/Backend/server.js
@@ -1,47 +1,50 @@
 require('dotenv').config();
 const express = require('express');
 const mongoose = require('mongoose');
+const cors = require('cors');
 const snackRoutes = require('./snackroutes');
 const mysqlData = require('./routes/SqlSnack');
-const cors = require('cors');
+const authRoutes = require('./routes/auth');
 
 const app = express();
-const PORT = 3000;
+const PORT =  3000;
 
 // Middleware
 app.use(express.json());
 app.use(cors({
-    origin: ['http://localhost:5173','https://asap-snackslam.netlify.app'], // Allow requests from your frontend
+    origin: ['http://localhost:5173', 'https://asap-snackslam.netlify.app'], // Allowed frontend origins
     methods: ['GET', 'POST', 'PUT', 'DELETE'],
-    credentials: true // Enable cookies or authentication headers if needed
+    credentials: true // Allow cookies and authentication headers
 }));
 
-// Connect to MongoDB using Mongoose
+// MongoDB Connection
 mongoose.connect(process.env.MONGO_URI, {
     useNewUrlParser: true,
     useUnifiedTopology: true
 })
-    .then(() => {
-        app.listen(PORT, () => {
-            console.log(`Hi, my name is Kartikay Rattan. Server is running at http://localhost:${PORT}`);
-        });
-        console.log('Database connected successfully');
-    })
-    .catch((error) => {
-        console.error('Database connection failed:', error.message);
-        process.exit(1);
+.then(() => {
+    console.log('✅ MongoDB Connected Successfully');
+    app.listen(PORT, () => {
+        console.log(`🚀 Server is running at http://localhost:${PORT}`);
     });
+})
+.catch((error) => {
+    console.error('❌ MongoDB Connection Failed:', error.message);
+    process.exit(1);
+});
 
-// Base route
+// Routes
 app.get('/', (req, res) => {
-    res.send(`<h1>Welcome to SnackSlam API!</h1>`);
+    res.send(`<h1>Welcome to SnackSlam API 🎉</h1><p>Your go-to snack rating platform!</p>`);
 });
 
-// Ping route
 app.get('/ping', (req, res) => {
-    res.send('Pong!');
+    res.send('Pong! 🏓');
 });
 
-// Use the routes from snackRoutes.js
-app.use('/api', snackRoutes);
-app.use('/sql', mysqlData);
+// API Routes
+app.use('/api/snacks', snackRoutes); // Adjusted path for better API structure
+app.use('/api/auth', authRoutes);
+app.use('/api/sql', mysqlData); // Unified API path structure
+
+module.exports = app;
diff --git a/Frontend/client/src/pages/LandingPage.jsx b/Frontend/client/src/pages/LandingPage.jsx
index 7332092..3777693 100644
--- a/Frontend/client/src/pages/LandingPage.jsx
+++ b/Frontend/client/src/pages/LandingPage.jsx
@@ -5,7 +5,7 @@ import AddSnack from "../pages/AddSnack";
 import SnackList from "../components/SnackList";
 import { getSnacks } from "../services/api";
 import { Link } from 'react-router-dom';
-
+import axios from "axios";
 const LandingPage = () => {
   const [isLoggedIn, setIsLoggedIn] = useState(false);
   const [username, setUsername] = useState("");
@@ -19,22 +19,49 @@ const handleSnackAdded = () => {
      setRefresh(!refresh); // Trigger refresh
 };
 
-  useEffect(() => {
-    document.title = "SnackSlam - Discover Overrated Snacks";
-  }, []);
-
-  const handleLogin = () => {
-    if (username) {
-      setIsLoggedIn(true);
+useEffect(() => {
+  document.title = "SnackSlam - Discover Overrated Snacks";
+  const checkAuth = async () => {
+    try {
+      const response = await axios.get("http://localhost:3000/api/auth/check-auth", {
+        withCredentials: true,
+        headers: { Authorization: `Bearer ${localStorage.getItem("token")}` },
+      });
+      console.log("Auth Status:", response.data);
+    } catch (error) {
+      console.error("Auth check failed", error);
     }
   };
 
-  const handleLogout = () => {
-    setIsLoggedIn(false);
-    setUsername("");
-    setShowSnackCard(false); // Reset SnackCard visibility on logout
-    setSnacks([]); // Clear snack data on logout
-  };
+  checkAuth();
+}, []);
+
+
+const handleLogin = async () => {
+  try {
+      const response = await axios.post(
+          "http://localhost:3000/api/auth/login",
+          { username },
+          { withCredentials: true }
+      );
+      setIsLoggedIn(true);
+      setUsername(response.data.username);
+  } catch (error) {
+      alert("Login failed. Try again.");
+  }
+};
+
+
+const handleLogout = async () => {
+  try {
+      await axios.post("http://localhost:3000/api/auth/logout", {}, { withCredentials: true });
+      setIsLoggedIn(false);
+      setUsername("");
+  } catch (error) {
+      alert("Logout failed. Try again.");
+  }
+};
+
 
   const handleGetSnackCard = () => {
     setShowSnackCard(true);
@@ -100,7 +127,7 @@ const handleSnackAdded = () => {
         <button
           className="landing-button"
           onClick={handleLogin}
-          disabled={!username}
+          disabled={!username.trim()}
         >
           🚀 Start Exploring
         </button>
@@ -108,12 +135,11 @@ const handleSnackAdded = () => {
     );
   }
 
-  // Main Content (Visible after Login)
   return (
     <div className="main-content">
       <button className="logout-btn" onClick={handleLogout}>
-  🚪 Logout
-</button>
+        🚪 Logout
+      </button>
 
       <h2>Welcome, {username}! 🎉</h2>
       <p>Discover the snacks that have sparked debates worldwide!</p>


Reviews:
user: login: qodo-code-review[bot]
state: COMMENTED
author_association: CONTRIBUTOR
submitted_at: 2025-04-03T04:21:38Z
user: login: qodo-code-review[bot]
state: COMMENTED
author_association: CONTRIBUTOR
submitted_at: 2025-04-03T04:21:48Z
user: login: qodo-code-review[bot]
state: COMMENTED
author_association: CONTRIBUTOR
submitted_at: 2025-04-03T04:22:01Z

Review comments:
diff_hunk: @@ -0,0 +1,31 @@
+const express = require("express");
+const router = express.Router();
+
+// Dummy user data (in real projects, use a database)
+const users = ["John", "Alice", "Bob","Kartikay","Diven","Aryaman","Akshit","Thakoor","Rishi","Chris","Krish"];
+
+router.post("/login", (req, res) => {
+    const { username } = req.body;
+    if (!username || !users.includes(username)) {
+        return res.status(401).json({ message: "Invalid username" });
+    }
+    res.cookie("username", username, { httpOnly: true, sameSite: "Strict" });
+    res.json({ message: "Login successful", username });
+});
+
+router.post("/logout", (req, res) => {
+    res.clearCookie("username");
+    res.json({ message: "Logged out successfully" });
+});
+
+router.get('/check-auth', async (req, res) => {
+    try {
+      res.json({ isAuthenticated: true, user: req.user });
+    } catch (error) {
+      console.error('Check Auth Error:', error);
+      res.status(500).json({ message: 'Internal Server Error' });
+    }
+  });
path: Backend/routes/auth.js
user: login: qodo-code-review[bot]
body: **Suggestion:** Fix authentication verification logic
```suggestion
router.get('/check-auth', async (req, res) => {
    try {
      const username = req.cookies.username;
      res.json({ 
        isAuthenticated: !!username, 
        user: username ? { username } : null 
      });
    } catch (error) {
      console.error('Check Auth Error:', error);
      res.status(500).json({ message: 'Internal Server Error' });
    }
  });
```

<!-- manually_applied -->
created_at: 2025-04-03T04:21:38Z
author_association: CONTRIBUTOR
diff_hunk: @@ -1,47 +1,50 @@
 require('dotenv').config();
 const express = require('express');
 const mongoose = require('mongoose');
+const cors = require('cors');
 const snackRoutes = require('./snackroutes');
 const mysqlData = require('./routes/SqlSnack');
-const cors = require('cors');
+const authRoutes = require('./routes/auth');
 
 const app = express();
-const PORT = 3000;
+const PORT =  3000;
 
 // Middleware
 app.use(express.json());
 app.use(cors({
-    origin: ['http://localhost:5173','https://asap-snackslam.netlify.app'], // Allow requests from your frontend
+    origin: ['http://localhost:5173', 'https://asap-snackslam.netlify.app'], // Allowed frontend origins
     methods: ['GET', 'POST', 'PUT', 'DELETE'],
-    credentials: true // Enable cookies or authentication headers if needed
+    credentials: true // Allow cookies and authentication headers
 }));
path: Backend/server.js
user: login: qodo-code-review[bot]
body: **Suggestion:** Add missing cookie-parser middleware
```suggestion
// Middleware
app.use(express.json());
app.use(cors({
    origin: ['http://localhost:5173', 'https://asap-snackslam.netlify.app'], // Allowed frontend origins
    methods: ['GET', 'POST', 'PUT', 'DELETE'],
    credentials: true // Allow cookies and authentication headers
}));
const cookieParser = require('cookie-parser');
app.use(cookieParser());
```

<!-- manually_applied -->
created_at: 2025-04-03T04:21:47Z
author_association: CONTRIBUTOR
diff_hunk: @@ -19,22 +19,49 @@ const handleSnackAdded = () => {
      setRefresh(!refresh); // Trigger refresh
 };
 
-  useEffect(() => {
-    document.title = "SnackSlam - Discover Overrated Snacks";
-  }, []);
-
-  const handleLogin = () => {
-    if (username) {
-      setIsLoggedIn(true);
+useEffect(() => {
+  document.title = "SnackSlam - Discover Overrated Snacks";
+  const checkAuth = async () => {
+    try {
+      const response = await axios.get("http://localhost:3000/api/auth/check-auth", {
+        withCredentials: true,
+        headers: { Authorization: `Bearer ${localStorage.getItem("token")}` },
+      });
+      console.log("Auth Status:", response.data);
+    } catch (error) {
+      console.error("Auth check failed", error);
     }
   };
 
-  const handleLogout = () => {
-    setIsLoggedIn(false);
-    setUsername("");
-    setShowSnackCard(false); // Reset SnackCard visibility on logout
-    setSnacks([]); // Clear snack data on logout
-  };
+  checkAuth();
+}, []);
path: Frontend/client/src/pages/LandingPage.jsx
user: login: qodo-code-review[bot]
body: **Suggestion:** Update state on authentication
```suggestion
useEffect(() => {
  document.title = "SnackSlam - Discover Overrated Snacks";
  const checkAuth = async () => {
    try {
      const response = await axios.get("http://localhost:3000/api/auth/check-auth", {
        withCredentials: true,
        headers: { Authorization: `Bearer ${localStorage.getItem("token")}` },
      });
      console.log("Auth Status:", response.data);
      if (response.data.isAuthenticated && response.data.user) {
        setIsLoggedIn(true);
        setUsername(response.data.user.username);
      }
    } catch (error) {
      console.error("Auth check failed", error);
    }
  };

  checkAuth();
}, []);
```

<!-- manually_applied -->
created_at: 2025-04-03T04:22:01Z
author_association: CONTRIBUTOR

PR comments:
user: login: netlify[bot]
created_at: 2025-04-03T04:20:45Z
body: ### <span aria-hidden="true">✅</span> Deploy Preview for *asap-snackslam* ready!


|  Name | Link |
|:-:|------------------------|
|<span aria-hidden="true">🔨</span> Latest commit | a6a4dc9767d0621f99dabb7c3a39a0f9fefee23b |
|<span aria-hidden="true">🔍</span> Latest deploy log | https://app.netlify.com/sites/asap-snackslam/deploys/67ee0c94a14ebc00085411f2 |
|<span aria-hidden="true">😎</span> Deploy Preview | [https://deploy-preview-28--asap-snackslam.netlify.app](https://deploy-preview-28--asap-snackslam.netlify.app) |
|<span aria-hidden="true">📱</span> Preview on mobile | <details><summary> Toggle QR Code... </summary><br /><br />![QR Code](https://app.netlify.com/qr-code/eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1cmwiOiJodHRwczovL2RlcGxveS1wcmV2aWV3LTI4LS1hc2FwLXNuYWNrc2xhbS5uZXRsaWZ5LmFwcCJ9.-QCe4e5lUihtjgTgn0eKofAN9zPb3zkH6N2SFhhBkEw)<br /><br />_Use your smartphone camera to open QR code link._</details> |
---
<!-- [asap-snackslam Preview](https://deploy-preview-28--asap-snackslam.netlify.app) -->
_To edit notification comments on pull requests, go to your [Netlify site configuration](https://app.netlify.com/sites/asap-snackslam/configuration/notifications#deploy-webhooks)._
author_association: NONE
user: login: qodo-code-review[bot]
created_at: 2025-04-03T04:21:02Z
body: _Qodo Merge was enabled for this repository. To continue using it, please link your Git account with your Qodo account [here](https://app.qodo.ai/qodo-merge)._

## PR Reviewer Guide 🔍

Here are some key observations to aid the review process:

<table>
<tr><td>⏱️&nbsp;<strong>Estimated effort to review</strong>: 3 🔵🔵🔵⚪⚪</td></tr>
<tr><td>🧪&nbsp;<strong>No relevant tests</strong></td></tr>
<tr><td>🔒&nbsp;<strong>Security concerns</strong><br><br>

<strong>Cookie security concerns:</strong><br> The authentication implementation uses HttpOnly cookies which is good, but there's no expiration set on the cookie in the login route. Without an expiration time, the cookie becomes a session cookie that persists until the browser is closed, which could lead to prolonged authentication sessions. Additionally, there's no CSRF protection implemented when using cookies for authentication.</td></tr>
<tr><td>⚡&nbsp;<strong>Recommended focus areas for review</strong><br><br>

<details><summary><a href='https://github.com/kalviumcommunity/S_84_SnackSlam/pull/28/files#diff-f88821281eb8c7054e20c1280d0d498ec636028245285c0d47e227938bc62e32R21-R28'><strong>Authentication Bug</strong></a>

The check-auth endpoint returns isAuthenticated: true and req.user without actually checking if the user is authenticated or if req.user exists. This will cause incorrect authentication status to be returned.
</summary>

```javascript
router.get('/check-auth', async (req, res) => {
    try {
      res.json({ isAuthenticated: true, user: req.user });
    } catch (error) {
      console.error('Check Auth Error:', error);
      res.status(500).json({ message: 'Internal Server Error' });
    }
  });
```

</details>

<details><summary><a href='https://github.com/kalviumcommunity/S_84_SnackSlam/pull/28/files#diff-9b857c8b68b98bd12bb0c287d2547561526eb3b3a38d9dac7f443b3cf7b44001R24-R37'><strong>Auth Check Logic</strong></a>

The checkAuth function doesn't update the application state (isLoggedIn and username) based on the authentication response, making the auth check ineffective.
</summary>

```jsx
  const checkAuth = async () => {
    try {
      const response = await axios.get("http://localhost:3000/api/auth/check-auth", {
        withCredentials: true,
        headers: { Authorization: `Bearer ${localStorage.getItem("token")}` },
      });
      console.log("Auth Status:", response.data);
    } catch (error) {
      console.error("Auth check failed", error);
    }
  };

  checkAuth();
}, []);
```

</details>

<details><summary><a href='https://github.com/kalviumcommunity/S_84_SnackSlam/pull/28/files#diff-6ccbaf6041c44c73c4e29f8c1ea8cf0e4059302f9d086525e63773bf00115f4aR12-R18'><strong>Missing Middleware</strong></a>

Cookie-parser middleware is imported in package.json but not configured in server.js, which is required for the cookie-based authentication to work properly.
</summary>

```javascript
// Middleware
app.use(express.json());
app.use(cors({
    origin: ['http://localhost:5173', 'https://asap-snackslam.netlify.app'], // Allowed frontend origins
    methods: ['GET', 'POST', 'PUT', 'DELETE'],
    credentials: true // Allow cookies and authentication headers
}));
```

</details>

</td></tr>
</table>

author_association: CONTRIBUTOR
user: login: qodo-code-review[bot]
created_at: 2025-04-03T04:21:24Z
body: _Qodo Merge was enabled for this repository. To continue using it, please link your Git account with your Qodo account [here](https://app.qodo.ai/qodo-merge)._

## PR Code Suggestions ✨

<!-- a6a4dc9 -->

Explore these optional code suggestions:

<table><thead><tr><td><strong>Category</strong></td><td align=left><strong>Suggestion&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </strong></td><td align=center><strong>Impact</strong></td></tr><tbody><tr><td rowspan=3>Possible issue</td>
<td>



<details><summary>✅ 
Fix authentication verification logic
</summary>

___


**The <code>/check-auth</code> endpoint always returns <code>isAuthenticated: true</code> regardless of <br>whether the user is actually authenticated. You should check for the presence of <br>the username cookie and only return true if it exists.**

[Backend/routes/auth.js [21-28]](https://github.com/kalviumcommunity/S_84_SnackSlam/pull/28/files#diff-f88821281eb8c7054e20c1280d0d498ec636028245285c0d47e227938bc62e32R21-R28)

```diff
 router.get('/check-auth', async (req, res) => {
     try {
-      res.json({ isAuthenticated: true, user: req.user });
+      const username = req.cookies.username;
+      res.json({ 
+        isAuthenticated: !!username, 
+        user: username ? { username } : null 
+      });
     } catch (error) {
       console.error('Check Auth Error:', error);
       res.status(500).json({ message: 'Internal Server Error' });
     }
   });
```

`[Suggestion has been applied]`

<details><summary>Suggestion importance[1-10]: 9</summary>

__

Why: The current implementation always returns isAuthenticated as true regardless of actual authentication status, which is a critical security issue. The fix properly checks for the username cookie and only returns true if authenticated.


</details></details></td><td align=center>High

</td></tr><tr><td>



<details><summary>✅ 
Add missing cookie-parser middleware
</summary>

___


**You've added cookie-based authentication but haven't configured the <br>cookie-parser middleware which is required to read cookies in Express. Add the <br>cookie-parser middleware after installing it.**

[Backend/server.js [12-18]](https://github.com/kalviumcommunity/S_84_SnackSlam/pull/28/files#diff-6ccbaf6041c44c73c4e29f8c1ea8cf0e4059302f9d086525e63773bf00115f4aR12-R18)

```diff
 // Middleware
 app.use(express.json());
 app.use(cors({
     origin: ['http://localhost:5173', 'https://asap-snackslam.netlify.app'], // Allowed frontend origins
     methods: ['GET', 'POST', 'PUT', 'DELETE'],
     credentials: true // Allow cookies and authentication headers
 }));
+const cookieParser = require('cookie-parser');
+app.use(cookieParser());
```

`[Suggestion has been applied]`

<details><summary>Suggestion importance[1-10]: 8</summary>

__

Why: The PR adds cookie-based authentication but fails to configure cookie-parser middleware, which is essential for reading cookies in Express. Without this, the authentication system won't work properly.


</details></details></td><td align=center>Medium

</td></tr><tr><td>



<details><summary>✅ 
Update state on authentication
</summary>

___


**The authentication check doesn't update the application state. You should use <br>the response from the <code>/check-auth</code> endpoint to set the login state and username <br>if the user is already authenticated.**

[Frontend/client/src/pages/LandingPage.jsx [22-37]](https://github.com/kalviumcommunity/S_84_SnackSlam/pull/28/files#diff-9b857c8b68b98bd12bb0c287d2547561526eb3b3a38d9dac7f443b3cf7b44001R22-R37)

```diff
 useEffect(() => {
   document.title = "SnackSlam - Discover Overrated Snacks";
   const checkAuth = async () => {
     try {
       const response = await axios.get("http://localhost:3000/api/auth/check-auth", {
         withCredentials: true,
         headers: { Authorization: `Bearer ${localStorage.getItem("token")}` },
       });
       console.log("Auth Status:", response.data);
+      if (response.data.isAuthenticated && response.data.user) {
+        setIsLoggedIn(true);
+        setUsername(response.data.user.username);
+      }
     } catch (error) {
       console.error("Auth check failed", error);
     }
   };
 
   checkAuth();
 }, []);
```

`[Suggestion has been applied]`

<details><summary>Suggestion importance[1-10]: 7</summary>

__

Why: The current implementation performs an authentication check but doesn't update the application state based on the result, leaving users logged out even if they have a valid session. This fix properly maintains user sessions.


</details></details></td><td align=center>Medium

</td></tr>
<tr><td align="center" colspan="2">

- [ ] More <!-- /improve --more_suggestions=true -->

</td><td></td></tr></tbody></table>


author_association: CONTRIBUTOR