From c84f182a7ed2b00f6b9c9a2c7fbd557801269b9f Mon Sep 17 00:00:00 2001 From: Hussein Bahdon <35459369+H-BAHDON@users.noreply.github.com> Date: Fri, 15 Sep 2023 13:07:48 +0100 Subject: [PATCH 01/33] Updated --- app/controllers/authController.js | 11 +++++++++++ app/routes/authRoutes.js | 1 + 2 files changed, 12 insertions(+) diff --git a/app/controllers/authController.js b/app/controllers/authController.js index 9e0b596..de62cd9 100644 --- a/app/controllers/authController.js +++ b/app/controllers/authController.js @@ -9,8 +9,18 @@ function platform(req, res) { function homePage(req, res) { res.send("Home page running well.") +// query db + // handleScore(req, res); } + +function handleScore (req, res){ + res.send("score is created"); + +} + + + function getUser(req, res) { if (req.isAuthenticated()) { const userId = req.user.id; // Assuming you have a unique identifier for users @@ -68,4 +78,5 @@ module.exports = { getUser, checkSession, logout, + handleScore, }; diff --git a/app/routes/authRoutes.js b/app/routes/authRoutes.js index edb013a..96df294 100644 --- a/app/routes/authRoutes.js +++ b/app/routes/authRoutes.js @@ -4,6 +4,7 @@ const authController = require('../controllers/authController'); // const { isLoggedIn } = require('../middleware/authenticationMiddleware'); router.get('/', authController.homePage) +router.get('/score', authController.handleScore) router.get('/platform', authController.platform); router.get('/user', authController.getUser); // router.get('/protected', isLoggedIn, authController.protected); From c3f763023bbad6324c9559f45be206791e9f6e75 Mon Sep 17 00:00:00 2001 From: Hussein Bahdon <35459369+H-BAHDON@users.noreply.github.com> Date: Fri, 15 Sep 2023 13:19:38 +0100 Subject: [PATCH 02/33] Updated scores --- app/controllers/authController.js | 15 +++++++++++++-- app/routes/authRoutes.js | 1 + 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/app/controllers/authController.js b/app/controllers/authController.js index de62cd9..031880b 100644 --- a/app/controllers/authController.js +++ b/app/controllers/authController.js @@ -14,9 +14,20 @@ function homePage(req, res) { } -function handleScore (req, res){ - res.send("score is created"); +async function handleScore(req, res) { + try { + const { score } = req.body; + console.log(`Received score: ${score}`); + + // Insert the score into your database table + const query = 'INSERT INTO users (total_score) VALUES (?)'; + await db.query(query, [score]); + res.json({ message: 'Score saved successfully' }); + } catch (error) { + console.error('Error saving score:', error); + res.status(500).json({ error: 'Error saving score' }); + } } diff --git a/app/routes/authRoutes.js b/app/routes/authRoutes.js index 96df294..679a750 100644 --- a/app/routes/authRoutes.js +++ b/app/routes/authRoutes.js @@ -5,6 +5,7 @@ const authController = require('../controllers/authController'); router.get('/', authController.homePage) router.get('/score', authController.handleScore) +router.post('/save-score', authController.handleScore); router.get('/platform', authController.platform); router.get('/user', authController.getUser); // router.get('/protected', isLoggedIn, authController.protected); From 7e320719a89eda6dc9ba4b9ef194e423a8fd6853 Mon Sep 17 00:00:00 2001 From: Hussein Bahdon <35459369+H-BAHDON@users.noreply.github.com> Date: Fri, 15 Sep 2023 13:38:16 +0100 Subject: [PATCH 03/33] Updated score --- app/controllers/authController.js | 10 +++++++++- app/routes/authRoutes.js | 2 +- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/app/controllers/authController.js b/app/controllers/authController.js index 031880b..ccd54e4 100644 --- a/app/controllers/authController.js +++ b/app/controllers/authController.js @@ -15,6 +15,14 @@ function homePage(req, res) { async function handleScore(req, res) { + try { + } catch (error) { + console.error('Error handling score:', error); + res.status(500).json({ error: 'Error handling score' }); + } +} + +async function saveScore(req, res) { try { const { score } = req.body; console.log(`Received score: ${score}`); @@ -31,7 +39,6 @@ async function handleScore(req, res) { } - function getUser(req, res) { if (req.isAuthenticated()) { const userId = req.user.id; // Assuming you have a unique identifier for users @@ -90,4 +97,5 @@ module.exports = { checkSession, logout, handleScore, + saveScore, }; diff --git a/app/routes/authRoutes.js b/app/routes/authRoutes.js index 679a750..b22cdc1 100644 --- a/app/routes/authRoutes.js +++ b/app/routes/authRoutes.js @@ -5,7 +5,7 @@ const authController = require('../controllers/authController'); router.get('/', authController.homePage) router.get('/score', authController.handleScore) -router.post('/save-score', authController.handleScore); +router.post('/save-score', authController.saveScore); router.get('/platform', authController.platform); router.get('/user', authController.getUser); // router.get('/protected', isLoggedIn, authController.protected); From da03625f4a6d058a7ff692d3c5fafe8079b5db2a Mon Sep 17 00:00:00 2001 From: Hussein Bahdon <35459369+H-BAHDON@users.noreply.github.com> Date: Fri, 15 Sep 2023 13:49:47 +0100 Subject: [PATCH 04/33] Updated authController.js --- app/controllers/authController.js | 1 + 1 file changed, 1 insertion(+) diff --git a/app/controllers/authController.js b/app/controllers/authController.js index ccd54e4..4141289 100644 --- a/app/controllers/authController.js +++ b/app/controllers/authController.js @@ -39,6 +39,7 @@ async function saveScore(req, res) { } + function getUser(req, res) { if (req.isAuthenticated()) { const userId = req.user.id; // Assuming you have a unique identifier for users From 4dffa11a5f42cb9e0eace4cc565880e210213393 Mon Sep 17 00:00:00 2001 From: Hussein Bahdon <35459369+H-BAHDON@users.noreply.github.com> Date: Fri, 15 Sep 2023 14:02:34 +0100 Subject: [PATCH 05/33] Updated authController.js --- app/controllers/authController.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/app/controllers/authController.js b/app/controllers/authController.js index 4141289..3369f7a 100644 --- a/app/controllers/authController.js +++ b/app/controllers/authController.js @@ -27,8 +27,8 @@ async function saveScore(req, res) { const { score } = req.body; console.log(`Received score: ${score}`); - // Insert the score into your database table const query = 'INSERT INTO users (total_score) VALUES (?)'; + console.log('SQL Query:', query); await db.query(query, [score]); res.json({ message: 'Score saved successfully' }); @@ -40,6 +40,7 @@ async function saveScore(req, res) { + function getUser(req, res) { if (req.isAuthenticated()) { const userId = req.user.id; // Assuming you have a unique identifier for users From 19165e3d825c682eb1927ff06e8839a48d0b27ba Mon Sep 17 00:00:00 2001 From: Hussein Bahdon <35459369+H-BAHDON@users.noreply.github.com> Date: Fri, 15 Sep 2023 14:12:14 +0100 Subject: [PATCH 06/33] Updated authController.js --- app/controllers/authController.js | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/app/controllers/authController.js b/app/controllers/authController.js index 3369f7a..4906b69 100644 --- a/app/controllers/authController.js +++ b/app/controllers/authController.js @@ -25,13 +25,22 @@ async function handleScore(req, res) { async function saveScore(req, res) { try { const { score } = req.body; + + // Validate the score input + if (isNaN(score)) { + return res.status(400).json({ error: 'Invalid score value' }); + } + console.log(`Received score: ${score}`); const query = 'INSERT INTO users (total_score) VALUES (?)'; console.log('SQL Query:', query); + + // Insert the score into the database await db.query(query, [score]); - res.json({ message: 'Score saved successfully' }); + // Respond with additional information if needed + res.json({ message: 'Score saved successfully', insertedScore: score }); } catch (error) { console.error('Error saving score:', error); res.status(500).json({ error: 'Error saving score' }); From 12a4074c439ee3ebeea538df75d06404943c48ea Mon Sep 17 00:00:00 2001 From: Hussein Bahdon <35459369+H-BAHDON@users.noreply.github.com> Date: Fri, 15 Sep 2023 14:18:37 +0100 Subject: [PATCH 07/33] Updated authController.js --- app/controllers/authController.js | 18 +++++++----------- 1 file changed, 7 insertions(+), 11 deletions(-) diff --git a/app/controllers/authController.js b/app/controllers/authController.js index 4906b69..fb5f506 100644 --- a/app/controllers/authController.js +++ b/app/controllers/authController.js @@ -25,22 +25,18 @@ async function handleScore(req, res) { async function saveScore(req, res) { try { const { score } = req.body; - - // Validate the score input - if (isNaN(score)) { - return res.status(400).json({ error: 'Invalid score value' }); - } - console.log(`Received score: ${score}`); const query = 'INSERT INTO users (total_score) VALUES (?)'; console.log('SQL Query:', query); - - // Insert the score into the database - await db.query(query, [score]); - // Respond with additional information if needed - res.json({ message: 'Score saved successfully', insertedScore: score }); + // Attempt to execute the SQL query + const result = await db.query(query, [score]); + + // Check the result and log it + console.log('Query Result:', result); + + res.json({ message: 'Score saved successfully' }); } catch (error) { console.error('Error saving score:', error); res.status(500).json({ error: 'Error saving score' }); From 4ba5d703504072668a8bd9a77cc73e276f1615ea Mon Sep 17 00:00:00 2001 From: Hussein Bahdon <35459369+H-BAHDON@users.noreply.github.com> Date: Fri, 15 Sep 2023 14:28:12 +0100 Subject: [PATCH 08/33] Updated authController.js --- app/controllers/authController.js | 23 +++++++++++++---------- 1 file changed, 13 insertions(+), 10 deletions(-) diff --git a/app/controllers/authController.js b/app/controllers/authController.js index fb5f506..5b36957 100644 --- a/app/controllers/authController.js +++ b/app/controllers/authController.js @@ -27,16 +27,19 @@ async function saveScore(req, res) { const { score } = req.body; console.log(`Received score: ${score}`); - const query = 'INSERT INTO users (total_score) VALUES (?)'; - console.log('SQL Query:', query); - - // Attempt to execute the SQL query - const result = await db.query(query, [score]); - - // Check the result and log it - console.log('Query Result:', result); - - res.json({ message: 'Score saved successfully' }); + // Validate that 'score' is a valid numeric value + if (!isNaN(score)) { + // Construct the SQL query with the score embedded + const query = `INSERT INTO users (total_score) VALUES (${score})`; + console.log('SQL Query:', query); + + await db.query(query); + + res.json({ message: 'Score saved successfully' }); + } else { + // Handle invalid score + res.status(400).json({ error: 'Invalid score value' }); + } } catch (error) { console.error('Error saving score:', error); res.status(500).json({ error: 'Error saving score' }); From 3e656e7838b6aef0e86a29328500c024ac8fbd8d Mon Sep 17 00:00:00 2001 From: Hussein Bahdon <35459369+H-BAHDON@users.noreply.github.com> Date: Fri, 15 Sep 2023 14:32:35 +0100 Subject: [PATCH 09/33] Updated authController.js --- app/controllers/authController.js | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/app/controllers/authController.js b/app/controllers/authController.js index 5b36957..43f2378 100644 --- a/app/controllers/authController.js +++ b/app/controllers/authController.js @@ -27,13 +27,20 @@ async function saveScore(req, res) { const { score } = req.body; console.log(`Received score: ${score}`); + // Check if the user is authenticated + if (!req.isAuthenticated()) { + return res.status(401).json({ error: 'Not authenticated' }); + } + + const userId = req.user.id; // Assuming you have a unique identifier for users + // Validate that 'score' is a valid numeric value if (!isNaN(score)) { - // Construct the SQL query with the score embedded - const query = `INSERT INTO users (total_score) VALUES (${score})`; + // Construct the SQL query to update the user's total_score + const query = 'UPDATE users SET total_score = total_score + $1 WHERE id = $2'; console.log('SQL Query:', query); - await db.query(query); + await db.query(query, [score, userId]); res.json({ message: 'Score saved successfully' }); } else { From fbe9b51398410bc63bead2ccebaf2fb06ee51831 Mon Sep 17 00:00:00 2001 From: Hussein Bahdon <35459369+H-BAHDON@users.noreply.github.com> Date: Fri, 15 Sep 2023 14:39:48 +0100 Subject: [PATCH 10/33] Updated authController.js --- app/controllers/authController.js | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/app/controllers/authController.js b/app/controllers/authController.js index 43f2378..ff440ee 100644 --- a/app/controllers/authController.js +++ b/app/controllers/authController.js @@ -34,9 +34,7 @@ async function saveScore(req, res) { const userId = req.user.id; // Assuming you have a unique identifier for users - // Validate that 'score' is a valid numeric value if (!isNaN(score)) { - // Construct the SQL query to update the user's total_score const query = 'UPDATE users SET total_score = total_score + $1 WHERE id = $2'; console.log('SQL Query:', query); @@ -56,6 +54,7 @@ async function saveScore(req, res) { + function getUser(req, res) { if (req.isAuthenticated()) { const userId = req.user.id; // Assuming you have a unique identifier for users From c9416abd0e2d41b557bbea691a0024b6d4f64d8d Mon Sep 17 00:00:00 2001 From: Hussein Bahdon <35459369+H-BAHDON@users.noreply.github.com> Date: Fri, 15 Sep 2023 15:03:45 +0100 Subject: [PATCH 11/33] Updated authController.js --- app/controllers/authController.js | 29 ++++++++++++++--------------- 1 file changed, 14 insertions(+), 15 deletions(-) diff --git a/app/controllers/authController.js b/app/controllers/authController.js index ff440ee..3be8978 100644 --- a/app/controllers/authController.js +++ b/app/controllers/authController.js @@ -25,25 +25,24 @@ async function handleScore(req, res) { async function saveScore(req, res) { try { const { score } = req.body; - console.log(`Received score: ${score}`); - // Check if the user is authenticated - if (!req.isAuthenticated()) { - return res.status(401).json({ error: 'Not authenticated' }); - } - - const userId = req.user.id; // Assuming you have a unique identifier for users + if (req.isAuthenticated()) { + if (!isNaN(score)) { + const userId = req.user.id; // Assuming you have a unique identifier for users + const query = 'UPDATE users SET total_score = total_score + $1 WHERE id = $2'; + console.log('SQL Query:', query); - if (!isNaN(score)) { - const query = 'UPDATE users SET total_score = total_score + $1 WHERE id = $2'; - console.log('SQL Query:', query); + await db.query(query, [score, userId]); - await db.query(query, [score, userId]); - - res.json({ message: 'Score saved successfully' }); + console.log('Score saved successfully'); + res.json({ message: 'Score saved successfully' }); + } else { + console.log('Invalid score value'); + res.status(400).json({ error: 'Invalid score value' }); + } } else { - // Handle invalid score - res.status(400).json({ error: 'Invalid score value' }); + console.log('Not authenticated'); + res.status(401).json({ error: 'Not authenticated' }); } } catch (error) { console.error('Error saving score:', error); From d709b31a804e3a024ef382cfd7205c1fe2f3a7be Mon Sep 17 00:00:00 2001 From: Hussein Bahdon <35459369+H-BAHDON@users.noreply.github.com> Date: Fri, 15 Sep 2023 15:08:49 +0100 Subject: [PATCH 12/33] Updated authController.js --- app/controllers/authController.js | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/app/controllers/authController.js b/app/controllers/authController.js index 3be8978..e6bfbc8 100644 --- a/app/controllers/authController.js +++ b/app/controllers/authController.js @@ -28,11 +28,11 @@ async function saveScore(req, res) { if (req.isAuthenticated()) { if (!isNaN(score)) { - const userId = req.user.id; // Assuming you have a unique identifier for users - const query = 'UPDATE users SET total_score = total_score + $1 WHERE id = $2'; + const userEmail = req.user.email; // Get the user's email + const query = 'UPDATE users SET total_score = total_score + $1 WHERE email = $2'; // Update based on email console.log('SQL Query:', query); - await db.query(query, [score, userId]); + await db.query(query, [score, userEmail]); console.log('Score saved successfully'); res.json({ message: 'Score saved successfully' }); @@ -41,7 +41,6 @@ async function saveScore(req, res) { res.status(400).json({ error: 'Invalid score value' }); } } else { - console.log('Not authenticated'); res.status(401).json({ error: 'Not authenticated' }); } } catch (error) { From 90b4679d7c96318c7ac81ff7b2233e984443bd53 Mon Sep 17 00:00:00 2001 From: Hussein Bahdon <35459369+H-BAHDON@users.noreply.github.com> Date: Fri, 15 Sep 2023 15:11:22 +0100 Subject: [PATCH 13/33] Updated authController.js --- app/controllers/authController.js | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/app/controllers/authController.js b/app/controllers/authController.js index e6bfbc8..8ea91bb 100644 --- a/app/controllers/authController.js +++ b/app/controllers/authController.js @@ -32,10 +32,15 @@ async function saveScore(req, res) { const query = 'UPDATE users SET total_score = total_score + $1 WHERE email = $2'; // Update based on email console.log('SQL Query:', query); - await db.query(query, [score, userEmail]); + const result = await db.query(query, [score, userEmail]); - console.log('Score saved successfully'); - res.json({ message: 'Score saved successfully' }); + if (result.rowCount === 1) { + console.log('Score saved successfully'); + res.json({ message: 'Score saved successfully' }); + } else { + console.log('No user found with the specified email'); + res.status(404).json({ error: 'User not found' }); + } } else { console.log('Invalid score value'); res.status(400).json({ error: 'Invalid score value' }); @@ -53,6 +58,7 @@ async function saveScore(req, res) { + function getUser(req, res) { if (req.isAuthenticated()) { const userId = req.user.id; // Assuming you have a unique identifier for users From 2e56e698327025d44a2da3155f8637e3a58c516c Mon Sep 17 00:00:00 2001 From: Hussein Bahdon <35459369+H-BAHDON@users.noreply.github.com> Date: Fri, 15 Sep 2023 15:15:05 +0100 Subject: [PATCH 14/33] Updated authController.js --- app/controllers/authController.js | 23 +++++++++++++++-------- 1 file changed, 15 insertions(+), 8 deletions(-) diff --git a/app/controllers/authController.js b/app/controllers/authController.js index 8ea91bb..117e96d 100644 --- a/app/controllers/authController.js +++ b/app/controllers/authController.js @@ -29,18 +29,24 @@ async function saveScore(req, res) { if (req.isAuthenticated()) { if (!isNaN(score)) { const userEmail = req.user.email; // Get the user's email - const query = 'UPDATE users SET total_score = total_score + $1 WHERE email = $2'; // Update based on email - console.log('SQL Query:', query); - const result = await db.query(query, [score, userEmail]); + // Retrieve the user's current total_score from the database + const getUserQuery = 'SELECT total_score FROM users WHERE email = $1'; + const userResult = await db.query(getUserQuery, [userEmail]); - if (result.rowCount === 1) { - console.log('Score saved successfully'); - res.json({ message: 'Score saved successfully' }); - } else { + if (userResult.rows.length === 0) { console.log('No user found with the specified email'); - res.status(404).json({ error: 'User not found' }); + return res.status(404).json({ error: 'User not found' }); } + + const currentTotalScore = userResult.rows[0].total_score; + + // Update the user's total_score in the database + const updateScoreQuery = 'UPDATE users SET total_score = $1 WHERE email = $2'; + await db.query(updateScoreQuery, [currentTotalScore + score, userEmail]); + + console.log('Score saved successfully'); + res.json({ message: 'Score saved successfully' }); } else { console.log('Invalid score value'); res.status(400).json({ error: 'Invalid score value' }); @@ -59,6 +65,7 @@ async function saveScore(req, res) { + function getUser(req, res) { if (req.isAuthenticated()) { const userId = req.user.id; // Assuming you have a unique identifier for users From 4af7760ff9b7294b0e7ed452e0eeecd536766ac6 Mon Sep 17 00:00:00 2001 From: Hussein Bahdon <35459369+H-BAHDON@users.noreply.github.com> Date: Fri, 15 Sep 2023 15:17:51 +0100 Subject: [PATCH 15/33] Updated authController.js --- app/controllers/authController.js | 38 +++++++++++++------------------ 1 file changed, 16 insertions(+), 22 deletions(-) diff --git a/app/controllers/authController.js b/app/controllers/authController.js index 117e96d..9cc7c87 100644 --- a/app/controllers/authController.js +++ b/app/controllers/authController.js @@ -26,33 +26,26 @@ async function saveScore(req, res) { try { const { score } = req.body; - if (req.isAuthenticated()) { - if (!isNaN(score)) { - const userEmail = req.user.email; // Get the user's email - - // Retrieve the user's current total_score from the database - const getUserQuery = 'SELECT total_score FROM users WHERE email = $1'; - const userResult = await db.query(getUserQuery, [userEmail]); + if (!req.isAuthenticated()) { + return res.status(401).json({ error: 'Not authenticated' }); + } - if (userResult.rows.length === 0) { - console.log('No user found with the specified email'); - return res.status(404).json({ error: 'User not found' }); - } + const userId = req.user.id; // Assuming you have a unique identifier for users - const currentTotalScore = userResult.rows[0].total_score; + // Validate that 'score' is a valid numeric value + if (!isNaN(score)) { + // Construct the SQL query with the score embedded + const query = 'UPDATE users SET total_score = total_score + $1 WHERE id = $2'; + console.log('SQL Query:', query); - // Update the user's total_score in the database - const updateScoreQuery = 'UPDATE users SET total_score = $1 WHERE email = $2'; - await db.query(updateScoreQuery, [currentTotalScore + score, userEmail]); + await db.query(query, [score, userId]); - console.log('Score saved successfully'); - res.json({ message: 'Score saved successfully' }); - } else { - console.log('Invalid score value'); - res.status(400).json({ error: 'Invalid score value' }); - } + console.log('Score saved successfully'); + res.json({ message: 'Score saved successfully' }); } else { - res.status(401).json({ error: 'Not authenticated' }); + // Handle invalid score + console.log('Invalid score value'); + res.status(400).json({ error: 'Invalid score value' }); } } catch (error) { console.error('Error saving score:', error); @@ -66,6 +59,7 @@ async function saveScore(req, res) { + function getUser(req, res) { if (req.isAuthenticated()) { const userId = req.user.id; // Assuming you have a unique identifier for users From 653bf38fa7a040e0d170010c42dced8d9281429d Mon Sep 17 00:00:00 2001 From: Hussein Bahdon <35459369+H-BAHDON@users.noreply.github.com> Date: Tue, 19 Sep 2023 15:12:28 +0100 Subject: [PATCH 16/33] Updated Back-end to Localhost --- .env | 14 ++++++++++---- .gitignore | 3 ++- Auth/githubStrategy.js | 2 +- Auth/googleStrategy.js | 2 +- app/app.js | 2 +- app/controllers/githubController.js | 4 ++-- 6 files changed, 17 insertions(+), 10 deletions(-) diff --git a/.env b/.env index 259d7ec..b09049d 100644 --- a/.env +++ b/.env @@ -4,11 +4,17 @@ NODE_ENV=production PORT=3001 -# REACT_APP_API_URL=http://localhost:3001 -REACT_APP_API_URL='https://mm-code-api-b4f2aff44087.herokuapp.com' +REACT_APP_API_URL=http://localhost:3001 +# REACT_APP_API_URL='https://mm-code-api-b4f2aff44087.herokuapp.com' REACT_APP_SECRET_KEY=abcdef123456 -# Client_SIDE_BASE_URL=http://localhost:3000 -Client_SIDE_BASE_URL=https://www.mmcode.io \ No newline at end of file +Client_SIDE_BASE_URL="http://localhost:3000" +# Client_SIDE_BASE_URL=https://www.mmcode.io + +GOOGLE_CLIENT_SECRET="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" +GOOGLE_CLIENT_ID="617409105699-u5senri6ujm3b655n5gkb0g6f7r8r5j1.apps.googleusercontent.com" + +GITHUB_CLIENT_ID="613427a2df3476638f43" +GITHUB_CLIENT_SECRET="417c54c316a47b3ead02087f71bce99b75c856bf" \ No newline at end of file diff --git a/.gitignore b/.gitignore index 40b878d..713d500 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ -node_modules/ \ No newline at end of file +node_modules/ +.env diff --git a/Auth/githubStrategy.js b/Auth/githubStrategy.js index 797fe90..40c8efc 100644 --- a/Auth/githubStrategy.js +++ b/Auth/githubStrategy.js @@ -6,7 +6,7 @@ const db = require('../config/db/db'); // Import your database configuration const githubStrategy = new GitHubStrategy({ clientID: process.env.GITHUB_CLIENT_ID, clientSecret: process.env.GITHUB_CLIENT_SECRET, - callbackURL: `https://mm-code-api-b4f2aff44087.herokuapp.com/auth/github/callback`, + callbackURL: `${process.env.REACT_APP_API_URL}/auth/github/callback`, scope: ['user:email'], }, async function (accessToken, refreshToken, profile, done) { diff --git a/Auth/googleStrategy.js b/Auth/googleStrategy.js index b05a357..e7ae14e 100644 --- a/Auth/googleStrategy.js +++ b/Auth/googleStrategy.js @@ -4,7 +4,7 @@ const db = require('../config/db/db'); // Import your database configuration const googleStrategy = new GoogleStrategy({ clientID: process.env.GOOGLE_CLIENT_ID, clientSecret: process.env.GOOGLE_CLIENT_SECRET, - callbackURL: `https://mm-code-api-b4f2aff44087.herokuapp.com/auth/google/callback`, + callbackURL: `${process.env.REACT_APP_API_URL}/auth/google/callback`, passReqToCallback: true, }, function (request, accessToken, refreshToken, profile, done) { diff --git a/app/app.js b/app/app.js index c737c5e..809e8b1 100644 --- a/app/app.js +++ b/app/app.js @@ -23,7 +23,7 @@ app.set('view engine', 'ejs'); app.use(cookieParser()); app.use( cors({ - origin: 'https://www.mmcode.io', + origin: ['https://www.mmcode.io', 'http://localhost:3000'], methods: ['GET', 'POST'], credentials: true, }) diff --git a/app/controllers/githubController.js b/app/controllers/githubController.js index 1752360..a43346b 100644 --- a/app/controllers/githubController.js +++ b/app/controllers/githubController.js @@ -8,14 +8,14 @@ function githubAuth(req, res, next) { function githubCallback(req, res, next){ passport.authenticate('github', { failureRedirect: '/login' })(req, res, function() { console.log("GitHub authentication successful:", req.user); - res.redirect(`${process.env.Client_SIDE_BASE_URL}/platform`); + res.redirect(`http://localhost:3001/platform`); }); } function githubSuccess(req, res) { console.log("GitHub authentication successful:", req.user); - res.redirect(`${process.env.Client_SIDE_BASE_URL}/platform`); + res.redirect(`http://localhost:3001/platform`); } function getGitHubUser(req, res) { From 15761e4346ee42a2cd71033a2b3d40682e202f79 Mon Sep 17 00:00:00 2001 From: Hussein Bahdon <35459369+H-BAHDON@users.noreply.github.com> Date: Tue, 19 Sep 2023 15:14:23 +0100 Subject: [PATCH 17/33] Updated githubController.js --- app/controllers/githubController.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/controllers/githubController.js b/app/controllers/githubController.js index a43346b..1752360 100644 --- a/app/controllers/githubController.js +++ b/app/controllers/githubController.js @@ -8,14 +8,14 @@ function githubAuth(req, res, next) { function githubCallback(req, res, next){ passport.authenticate('github', { failureRedirect: '/login' })(req, res, function() { console.log("GitHub authentication successful:", req.user); - res.redirect(`http://localhost:3001/platform`); + res.redirect(`${process.env.Client_SIDE_BASE_URL}/platform`); }); } function githubSuccess(req, res) { console.log("GitHub authentication successful:", req.user); - res.redirect(`http://localhost:3001/platform`); + res.redirect(`${process.env.Client_SIDE_BASE_URL}/platform`); } function getGitHubUser(req, res) { From bf4377e5033176de8ce745d94057d741f300bdec Mon Sep 17 00:00:00 2001 From: Hussein Bahdon <35459369+H-BAHDON@users.noreply.github.com> Date: Tue, 19 Sep 2023 16:08:48 +0100 Subject: [PATCH 18/33] Updated authController.js --- app/controllers/authController.js | 32 ++++++++++++++++++++++++++++--- 1 file changed, 29 insertions(+), 3 deletions(-) diff --git a/app/controllers/authController.js b/app/controllers/authController.js index 9cc7c87..a0b5e17 100644 --- a/app/controllers/authController.js +++ b/app/controllers/authController.js @@ -26,19 +26,33 @@ async function saveScore(req, res) { try { const { score } = req.body; - if (!req.isAuthenticated()) { + // Check session to verify authentication + const sessionCheckResponse = await checkSession(req); + + if (sessionCheckResponse.status === 401) { return res.status(401).json({ error: 'Not authenticated' }); } const userId = req.user.id; // Assuming you have a unique identifier for users + // Retrieve the user's email using a database query + const userQuery = 'SELECT email FROM users WHERE id = $1'; + const userResult = await db.query(userQuery, [userId]); + + if (userResult.rows.length === 0) { + console.error('User not found in the database'); + return res.status(500).json({ error: 'User not found in the database' }); + } + + const userEmail = userResult.rows[0].email; + // Validate that 'score' is a valid numeric value if (!isNaN(score)) { // Construct the SQL query with the score embedded - const query = 'UPDATE users SET total_score = total_score + $1 WHERE id = $2'; + const query = 'UPDATE users SET total_score = total_score + $1 WHERE email = $2'; console.log('SQL Query:', query); - await db.query(query, [score, userId]); + await db.query(query, [score, userEmail]); console.log('Score saved successfully'); res.json({ message: 'Score saved successfully' }); @@ -53,6 +67,18 @@ async function saveScore(req, res) { } } +async function checkSession(req) { + try { + if (req.isAuthenticated()) { + return { status: 200 }; + } else { + return { status: 401 }; + } + } catch (e) { + return { status: 500 }; + } +} + From b993e7705d49a6ba9b8b8ad3fa88f2f473b33bf5 Mon Sep 17 00:00:00 2001 From: Hussein Bahdon <35459369+H-BAHDON@users.noreply.github.com> Date: Tue, 19 Sep 2023 16:13:08 +0100 Subject: [PATCH 19/33] . --- app/controllers/authController.js | 23 +---------------------- 1 file changed, 1 insertion(+), 22 deletions(-) diff --git a/app/controllers/authController.js b/app/controllers/authController.js index a0b5e17..1027a88 100644 --- a/app/controllers/authController.js +++ b/app/controllers/authController.js @@ -26,10 +26,7 @@ async function saveScore(req, res) { try { const { score } = req.body; - // Check session to verify authentication - const sessionCheckResponse = await checkSession(req); - - if (sessionCheckResponse.status === 401) { + if (!req.isAuthenticated()) { return res.status(401).json({ error: 'Not authenticated' }); } @@ -67,24 +64,6 @@ async function saveScore(req, res) { } } -async function checkSession(req) { - try { - if (req.isAuthenticated()) { - return { status: 200 }; - } else { - return { status: 401 }; - } - } catch (e) { - return { status: 500 }; - } -} - - - - - - - function getUser(req, res) { if (req.isAuthenticated()) { From 5d7a3fa88bbf9edde4b9d929dd3f9cdd27bdc92c Mon Sep 17 00:00:00 2001 From: Hussein Bahdon <35459369+H-BAHDON@users.noreply.github.com> Date: Tue, 19 Sep 2023 16:29:10 +0100 Subject: [PATCH 20/33] . --- Auth/googleStrategy.js | 86 ++++++++++++++++++++----------- app/controllers/authController.js | 22 ++------ 2 files changed, 58 insertions(+), 50 deletions(-) diff --git a/Auth/googleStrategy.js b/Auth/googleStrategy.js index e7ae14e..fbbf482 100644 --- a/Auth/googleStrategy.js +++ b/Auth/googleStrategy.js @@ -1,47 +1,71 @@ const GoogleStrategy = require('passport-google-oauth20').Strategy; const db = require('../config/db/db'); // Import your database configuration -const googleStrategy = new GoogleStrategy({ - clientID: process.env.GOOGLE_CLIENT_ID, - clientSecret: process.env.GOOGLE_CLIENT_SECRET, - callbackURL: `${process.env.REACT_APP_API_URL}/auth/google/callback`, - passReqToCallback: true, -}, function (request, accessToken, refreshToken, profile, done) { - - const checkEmailQuery = 'SELECT * FROM users WHERE email = $1'; - const emailValue = [profile.emails[0].value]; - - db.query(checkEmailQuery, emailValue, (err, result) => { - if (err) { - return done(err); - } +export function updateUserScore(email, score) { + const updateScoreQuery = 'UPDATE users SET total_score = $1 WHERE email = $2'; + const updateScoreValues = [score, email]; + + return db.query(updateScoreQuery, updateScoreValues); +} + +const googleStrategy = new GoogleStrategy( + { + clientID: process.env.GOOGLE_CLIENT_ID, + clientSecret: process.env.GOOGLE_CLIENT_SECRET, + callbackURL: `${process.env.REACT_APP_API_URL}/auth/google/callback`, + passReqToCallback: true, + }, + async function (request, accessToken, refreshToken, profile, done) { + try { + const checkEmailQuery = 'SELECT * FROM users WHERE email = $1'; + const emailValue = [profile.emails[0].value]; + + const userResult = await db.query(checkEmailQuery, emailValue); - if (result.rows.length === 0) { - const insertUserQuery = 'INSERT INTO users (full_name, email, accounts) VALUES ($1, $2, $3)'; - const insertUserValues = [profile.displayName, profile.emails[0].value, 'Google']; // Set the account provider to 'Google' + if (userResult.rows.length === 0) { + const insertUserQuery = + 'INSERT INTO users (full_name, email, accounts) VALUES ($1, $2, $3)'; + const insertUserValues = [ + profile.displayName, + profile.emails[0].value, + 'Google', + ]; // Set the account provider to 'Google' + + await db.query(insertUserQuery, insertUserValues); + + const user = { + displayName: profile.displayName, + email: profile.emails[0].value, + accountProvider: 'Google', + }; - db.query(insertUserQuery, insertUserValues, (err) => { - if (err) { - return done(err); + // Check if the client has provided a score in the request + if (request.body && !isNaN(request.body.score)) { + const score = parseInt(request.body.score); + updateUserScore(user.email, score); } + return done(null, user); + } else { const user = { displayName: profile.displayName, email: profile.emails[0].value, - accountProvider: 'Google', + accountProvider: 'Google', }; + + // Check if the client has provided a score in the request + if (request.body && !isNaN(request.body.score)) { + const score = parseInt(request.body.score); + updateUserScore(user.email, score); + } + return done(null, user); - }); - } else { - const user = { - displayName: profile.displayName, - email: profile.emails[0].value, - accountProvider: 'Google', - }; - return done(null, user); + } + } catch (error) { + return done(error); } - }); -}); + } +); module.exports = googleStrategy; diff --git a/app/controllers/authController.js b/app/controllers/authController.js index 1027a88..347ecc7 100644 --- a/app/controllers/authController.js +++ b/app/controllers/authController.js @@ -1,4 +1,5 @@ const db = require('../../config/db/db'); +const { updateUserScore } = require('../../Auth/googleStrategy'); function platform(req, res) { req.session.randomValue = Math.random(); const storedRandomValue = req.session.randomValue; @@ -30,31 +31,14 @@ async function saveScore(req, res) { return res.status(401).json({ error: 'Not authenticated' }); } - const userId = req.user.id; // Assuming you have a unique identifier for users - - // Retrieve the user's email using a database query - const userQuery = 'SELECT email FROM users WHERE id = $1'; - const userResult = await db.query(userQuery, [userId]); - - if (userResult.rows.length === 0) { - console.error('User not found in the database'); - return res.status(500).json({ error: 'User not found in the database' }); - } - - const userEmail = userResult.rows[0].email; + const userEmail = req.user.email; - // Validate that 'score' is a valid numeric value if (!isNaN(score)) { - // Construct the SQL query with the score embedded - const query = 'UPDATE users SET total_score = total_score + $1 WHERE email = $2'; - console.log('SQL Query:', query); - - await db.query(query, [score, userEmail]); + await updateUserScore(userEmail, score); console.log('Score saved successfully'); res.json({ message: 'Score saved successfully' }); } else { - // Handle invalid score console.log('Invalid score value'); res.status(400).json({ error: 'Invalid score value' }); } From 7a585c49859e287be01b9565de5d6e7ed7f1c3dd Mon Sep 17 00:00:00 2001 From: Hussein Bahdon <35459369+H-BAHDON@users.noreply.github.com> Date: Tue, 19 Sep 2023 16:34:45 +0100 Subject: [PATCH 21/33] . --- Auth/googleStrategy.js | 86 +++++++++++++++--------------------------- 1 file changed, 31 insertions(+), 55 deletions(-) diff --git a/Auth/googleStrategy.js b/Auth/googleStrategy.js index fbbf482..e7ae14e 100644 --- a/Auth/googleStrategy.js +++ b/Auth/googleStrategy.js @@ -1,71 +1,47 @@ const GoogleStrategy = require('passport-google-oauth20').Strategy; const db = require('../config/db/db'); // Import your database configuration -export function updateUserScore(email, score) { - const updateScoreQuery = 'UPDATE users SET total_score = $1 WHERE email = $2'; - const updateScoreValues = [score, email]; - - return db.query(updateScoreQuery, updateScoreValues); -} - -const googleStrategy = new GoogleStrategy( - { - clientID: process.env.GOOGLE_CLIENT_ID, - clientSecret: process.env.GOOGLE_CLIENT_SECRET, - callbackURL: `${process.env.REACT_APP_API_URL}/auth/google/callback`, - passReqToCallback: true, - }, - async function (request, accessToken, refreshToken, profile, done) { - try { - const checkEmailQuery = 'SELECT * FROM users WHERE email = $1'; - const emailValue = [profile.emails[0].value]; - - const userResult = await db.query(checkEmailQuery, emailValue); - - if (userResult.rows.length === 0) { - const insertUserQuery = - 'INSERT INTO users (full_name, email, accounts) VALUES ($1, $2, $3)'; - const insertUserValues = [ - profile.displayName, - profile.emails[0].value, - 'Google', - ]; // Set the account provider to 'Google' - - await db.query(insertUserQuery, insertUserValues); +const googleStrategy = new GoogleStrategy({ + clientID: process.env.GOOGLE_CLIENT_ID, + clientSecret: process.env.GOOGLE_CLIENT_SECRET, + callbackURL: `${process.env.REACT_APP_API_URL}/auth/google/callback`, + passReqToCallback: true, +}, function (request, accessToken, refreshToken, profile, done) { + + const checkEmailQuery = 'SELECT * FROM users WHERE email = $1'; + const emailValue = [profile.emails[0].value]; + + db.query(checkEmailQuery, emailValue, (err, result) => { + if (err) { + return done(err); + } - const user = { - displayName: profile.displayName, - email: profile.emails[0].value, - accountProvider: 'Google', - }; + if (result.rows.length === 0) { + const insertUserQuery = 'INSERT INTO users (full_name, email, accounts) VALUES ($1, $2, $3)'; + const insertUserValues = [profile.displayName, profile.emails[0].value, 'Google']; // Set the account provider to 'Google' - // Check if the client has provided a score in the request - if (request.body && !isNaN(request.body.score)) { - const score = parseInt(request.body.score); - updateUserScore(user.email, score); + db.query(insertUserQuery, insertUserValues, (err) => { + if (err) { + return done(err); } - return done(null, user); - } else { const user = { displayName: profile.displayName, email: profile.emails[0].value, - accountProvider: 'Google', + accountProvider: 'Google', }; - - // Check if the client has provided a score in the request - if (request.body && !isNaN(request.body.score)) { - const score = parseInt(request.body.score); - updateUserScore(user.email, score); - } - return done(null, user); - } - } catch (error) { - return done(error); + }); + } else { + const user = { + displayName: profile.displayName, + email: profile.emails[0].value, + accountProvider: 'Google', + }; + return done(null, user); } - } -); + }); +}); module.exports = googleStrategy; From bc7ed94fe390ec9acf4acb3f759d102ed033a8e2 Mon Sep 17 00:00:00 2001 From: Hussein Bahdon <35459369+H-BAHDON@users.noreply.github.com> Date: Tue, 19 Sep 2023 16:38:06 +0100 Subject: [PATCH 22/33] authController.js --- app/controllers/authController.js | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/app/controllers/authController.js b/app/controllers/authController.js index 347ecc7..72bb82c 100644 --- a/app/controllers/authController.js +++ b/app/controllers/authController.js @@ -1,5 +1,4 @@ const db = require('../../config/db/db'); -const { updateUserScore } = require('../../Auth/googleStrategy'); function platform(req, res) { req.session.randomValue = Math.random(); const storedRandomValue = req.session.randomValue; @@ -33,12 +32,17 @@ async function saveScore(req, res) { const userEmail = req.user.email; + // Validate that 'score' is a valid numeric value if (!isNaN(score)) { - await updateUserScore(userEmail, score); + // Construct the SQL query with the score embedded + const query = 'UPDATE users SET total_score = total_score + $1 WHERE email = $2'; + + await db.query(query, [score, userEmail]); console.log('Score saved successfully'); res.json({ message: 'Score saved successfully' }); } else { + // Handle invalid score console.log('Invalid score value'); res.status(400).json({ error: 'Invalid score value' }); } From 870d4b2df1c0e75ae179befa417fec8e81e45d26 Mon Sep 17 00:00:00 2001 From: Hussein Bahdon <35459369+H-BAHDON@users.noreply.github.com> Date: Thu, 19 Oct 2023 15:57:48 +0100 Subject: [PATCH 23/33] Updated --- app/controllers/authController.js | 57 +++++++++++++++++++------- app/controllers/googleController.js | 27 +++++++++++-- app/controllers/tokens.js | 25 ++++++++++++ app/routes/authRoutes.js | 20 +++++++++- node_modules/.package-lock.json | 60 ++++++++++++++++++++++------ package-lock.json | 62 +++++++++++++++++++++++------ package.json | 2 +- 7 files changed, 206 insertions(+), 47 deletions(-) create mode 100644 app/controllers/tokens.js diff --git a/app/controllers/authController.js b/app/controllers/authController.js index 72bb82c..fde4938 100644 --- a/app/controllers/authController.js +++ b/app/controllers/authController.js @@ -1,4 +1,6 @@ const db = require('../../config/db/db'); +const { verifyToken, generateToken } = require('../controllers/tokens'); // Import your verifyToken function + function platform(req, res) { req.session.randomValue = Math.random(); const storedRandomValue = req.session.randomValue; @@ -13,6 +15,29 @@ function homePage(req, res) { // handleScore(req, res); } +async function login(req, res) { + try { + // Assuming you have user data from Google OAuth in req.user object + const { displayName, email } = req.user; + + // Generate a token + const token = generateToken({ displayName, email }); // Customize this based on your user data + + // Set the token in the response cookie + res.cookie('token', token, { + httpOnly: true, + secure: process.env.NODE_ENV === 'production', + maxAge: 24 * 60 * 60 * 1000, // 24 hours expiration + sameSite: 'none', + }); + + res.json({ message: 'User authenticated', token }); + } catch (error) { + console.error('Error authenticating user:', error); + res.status(500).json({ error: 'Internal server error' }); + } +} + async function handleScore(req, res) { try { @@ -29,20 +54,14 @@ async function saveScore(req, res) { if (!req.isAuthenticated()) { return res.status(401).json({ error: 'Not authenticated' }); } - const userEmail = req.user.email; - // Validate that 'score' is a valid numeric value if (!isNaN(score)) { - // Construct the SQL query with the score embedded const query = 'UPDATE users SET total_score = total_score + $1 WHERE email = $2'; - await db.query(query, [score, userEmail]); - console.log('Score saved successfully'); res.json({ message: 'Score saved successfully' }); } else { - // Handle invalid score console.log('Invalid score value'); res.status(400).json({ error: 'Invalid score value' }); } @@ -55,7 +74,7 @@ async function saveScore(req, res) { function getUser(req, res) { if (req.isAuthenticated()) { - const userId = req.user.id; // Assuming you have a unique identifier for users + const userId = req.user.id; db.query('SELECT full_name, email FROM users WHERE id = $1', [userId]) .then(result => { if (result.rows.length === 0) { @@ -88,17 +107,24 @@ function getUser(req, res) { function checkSession(req, res) { - try { - if (req.isAuthenticated()) { - res.sendStatus(200); - } else { - res.sendStatus(401); - } - } catch (e) { - return res.status(500).json({ msg: "Error found" }); + const token = req.cookies.session; // Assuming the token is stored in a cookie named 'token' + + if (!token) { + return res.status(401).json({ error: 'Unauthorized' }); } + + const decodedToken = verifyToken(token); + + if (!decodedToken) { + // Invalid or expired token + return res.status(401).json({ error: 'Unauthorized' }); + } + + // Token is valid, user is authenticated + return res.status(200).json({ message: 'User is authenticated' }); } + function logout(req, res) { req.logout(); res.status(200).json({ success : true }); @@ -112,4 +138,5 @@ module.exports = { logout, handleScore, saveScore, + login }; diff --git a/app/controllers/googleController.js b/app/controllers/googleController.js index 342d4c2..7e12843 100644 --- a/app/controllers/googleController.js +++ b/app/controllers/googleController.js @@ -1,22 +1,41 @@ const passport = require("passport"); +const jwt = require('jsonwebtoken'); -// Google OAuth authentication function googleAuth(req, res) { passport.authenticate('google', { scope: ['email', 'profile'] })(req, res); } -// Callback after Google OAuth authentication function googleCallback(req, res, next) { passport.authenticate('google', { successRedirect: `${process.env.Client_SIDE_BASE_URL}/platform`, failureRedirect: '/auth/google/failure' + }, (err, user) => { + if (err) { + return next(err); + } + if (!user) { + // Handle authentication failure + return res.redirect(`${process.env.Client_SIDE_BASE_URL}/login`); + } + + // Generate a JWT token + const token = jwt.sign(user, process.env.JWT_SECRET, { expiresIn: '24h' }); + + // Set the token in an HTTP-only cookie + res.cookie('token', token, { + httpOnly: true, + secure: process.env.NODE_ENV === 'production', + maxAge: 24 * 60 * 60 * 1000, // 24 hours expiration + sameSite: 'none', + }); + + // Redirect to the desired page after successful login + return res.redirect(`${process.env.Client_SIDE_BASE_URL}/platform`); })(req, res, next); } -// Failure route function googleFailure(req, res) { res.redirect(`${process.env.Client_SIDE_BASE_URL}/login`); - // Note: You should not use `res.send` after `res.redirect` as it will not be executed. } module.exports = { diff --git a/app/controllers/tokens.js b/app/controllers/tokens.js new file mode 100644 index 0000000..66d4eb1 --- /dev/null +++ b/app/controllers/tokens.js @@ -0,0 +1,25 @@ +const jwt = require('jsonwebtoken'); + +const secretKey = 'melly'; + +// Function to generate a JWT token +function generateToken(user) { + const token = jwt.sign({ user }, secretKey, { expiresIn: '24h' }); + return token; +} + +// Function to verify JWT token +function verifyToken(token) { + try { + const decoded = jwt.verify(token, secretKey); + return decoded; + } catch (error) { + // Token is invalid or expired + return null; + } +} + +module.exports = { + generateToken, + verifyToken, +}; diff --git a/app/routes/authRoutes.js b/app/routes/authRoutes.js index b22cdc1..9141088 100644 --- a/app/routes/authRoutes.js +++ b/app/routes/authRoutes.js @@ -2,13 +2,29 @@ const express = require('express'); const router = express.Router(); const authController = require('../controllers/authController'); // const { isLoggedIn } = require('../middleware/authenticationMiddleware'); +const { generateToken } = require('../controllers/tokens'); // Import your generateToken function router.get('/', authController.homePage) router.get('/score', authController.handleScore) router.post('/save-score', authController.saveScore); router.get('/platform', authController.platform); -router.get('/user', authController.getUser); -// router.get('/protected', isLoggedIn, authController.protected); +router.post('/login', authController.login); + + +router.get('/user', (req, res) => { + const token = generateToken(req.user); + res.cookie('token', token, { + httpOnly: true, + secure: process.env.NODE_ENV === 'production', + maxAge: 24 * 60 * 60 * 1000, + sameSite: 'none', + }); + res.json({ message: 'User authenticated', token }); + }); + + + // router.get('/protected', isLoggedIn, authController.protected); + router.get('/check-session', authController.checkSession) router.get('/logout', authController.logout); diff --git a/node_modules/.package-lock.json b/node_modules/.package-lock.json index a8b1334..393fde0 100644 --- a/node_modules/.package-lock.json +++ b/node_modules/.package-lock.json @@ -1355,14 +1355,20 @@ } }, "node_modules/jsonwebtoken": { - "version": "9.0.1", - "resolved": "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-9.0.1.tgz", - "integrity": "sha512-K8wx7eJ5TPvEjuiVSkv167EVboBDv9PZdDoF7BgeQnBLVvZWW9clr2PsQHVJDTKaEIH5JBIwHujGcHp7GgI2eg==", + "version": "9.0.2", + "resolved": "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-9.0.2.tgz", + "integrity": "sha512-PRp66vJ865SSqOlgqS8hujT5U4AOgMfhrwYIuIhfKaoSCZcirrmASQr8CX7cUg+RMih+hgznrjp99o+W4pJLHQ==", "dependencies": { "jws": "^3.2.2", - "lodash": "^4.17.21", + "lodash.includes": "^4.3.0", + "lodash.isboolean": "^3.0.3", + "lodash.isinteger": "^4.0.4", + "lodash.isnumber": "^3.0.3", + "lodash.isplainobject": "^4.0.6", + "lodash.isstring": "^4.0.1", + "lodash.once": "^4.0.0", "ms": "^2.1.1", - "semver": "^7.3.8" + "semver": "^7.5.4" }, "engines": { "node": ">=12", @@ -1404,10 +1410,40 @@ "node": ">= 0.6" } }, - "node_modules/lodash": { - "version": "4.17.21", - "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", - "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==" + "node_modules/lodash.includes": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/lodash.includes/-/lodash.includes-4.3.0.tgz", + "integrity": "sha512-W3Bx6mdkRTGtlJISOvVD/lbqjTlPPUDTMnlXZFnVwi9NKJ6tiAk6LVdlhZMm17VZisqhKcgzpO5Wz91PCt5b0w==" + }, + "node_modules/lodash.isboolean": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/lodash.isboolean/-/lodash.isboolean-3.0.3.tgz", + "integrity": "sha512-Bz5mupy2SVbPHURB98VAcw+aHh4vRV5IPNhILUCsOzRmsTmSQ17jIuqopAentWoehktxGd9e/hbIXq980/1QJg==" + }, + "node_modules/lodash.isinteger": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/lodash.isinteger/-/lodash.isinteger-4.0.4.tgz", + "integrity": "sha512-DBwtEWN2caHQ9/imiNeEA5ys1JoRtRfY3d7V9wkqtbycnAmTvRRmbHKDV4a0EYc678/dia0jrte4tjYwVBaZUA==" + }, + "node_modules/lodash.isnumber": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/lodash.isnumber/-/lodash.isnumber-3.0.3.tgz", + "integrity": "sha512-QYqzpfwO3/CWf3XP+Z+tkQsfaLL/EnUlXWVkIk5FUPc4sBdTehEqZONuyRt2P67PXAk+NXmTBcc97zw9t1FQrw==" + }, + "node_modules/lodash.isplainobject": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz", + "integrity": "sha512-oSXzaWypCMHkPC3NvBEaPHf0KsA5mvPrOPgQWDsbg8n7orZ290M0BmC/jgRZ4vcJ6DTAhjrsSYgdsW/F+MFOBA==" + }, + "node_modules/lodash.isstring": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/lodash.isstring/-/lodash.isstring-4.0.1.tgz", + "integrity": "sha512-0wJxfxH1wgO3GrbuP+dTTk7op+6L41QCXbGINEmD+ny/G/eCqGzxyCsh7159S+mgDDcoarnBw6PC1PS5+wUGgw==" + }, + "node_modules/lodash.once": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/lodash.once/-/lodash.once-4.1.1.tgz", + "integrity": "sha512-Sb487aTOCr9drQVL8pIxOzVhafOjZN9UU54hiN8PU3uAiSV7lx1yYNpbNmex2PK6dSJoNTSJUUswT651yww3Mg==" }, "node_modules/lru-cache": { "version": "6.0.0", @@ -2151,9 +2187,9 @@ "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==" }, "node_modules/semver": { - "version": "7.5.3", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.5.3.tgz", - "integrity": "sha512-QBlUtyVk/5EeHbi7X0fw6liDZc7BBmEaSYn01fMU1OUYbf6GPsbTtd8WmnqbI20SeycoHSeiybkE/q1Q+qlThQ==", + "version": "7.5.4", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.5.4.tgz", + "integrity": "sha512-1bCSESV6Pv+i21Hvpxp3Dx+pSD8lIPt8uVjRrxAUt/nbswYc+tK6Y2btiULjd4+fnq15PX+nqQDC7Oft7WkwcA==", "dependencies": { "lru-cache": "^6.0.0" }, diff --git a/package-lock.json b/package-lock.json index 9c09fed..398b7f7 100644 --- a/package-lock.json +++ b/package-lock.json @@ -22,7 +22,7 @@ "express-session": "^1.17.3", "fs": "^0.0.1-security", "google-auth-library": "^9.0.0", - "jsonwebtoken": "^9.0.1", + "jsonwebtoken": "^9.0.2", "morgan": "^1.10.0", "nodemailer": "^6.9.4", "nodemon": "^2.0.22", @@ -1398,14 +1398,20 @@ } }, "node_modules/jsonwebtoken": { - "version": "9.0.1", - "resolved": "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-9.0.1.tgz", - "integrity": "sha512-K8wx7eJ5TPvEjuiVSkv167EVboBDv9PZdDoF7BgeQnBLVvZWW9clr2PsQHVJDTKaEIH5JBIwHujGcHp7GgI2eg==", + "version": "9.0.2", + "resolved": "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-9.0.2.tgz", + "integrity": "sha512-PRp66vJ865SSqOlgqS8hujT5U4AOgMfhrwYIuIhfKaoSCZcirrmASQr8CX7cUg+RMih+hgznrjp99o+W4pJLHQ==", "dependencies": { "jws": "^3.2.2", - "lodash": "^4.17.21", + "lodash.includes": "^4.3.0", + "lodash.isboolean": "^3.0.3", + "lodash.isinteger": "^4.0.4", + "lodash.isnumber": "^3.0.3", + "lodash.isplainobject": "^4.0.6", + "lodash.isstring": "^4.0.1", + "lodash.once": "^4.0.0", "ms": "^2.1.1", - "semver": "^7.3.8" + "semver": "^7.5.4" }, "engines": { "node": ">=12", @@ -1447,10 +1453,40 @@ "node": ">= 0.6" } }, - "node_modules/lodash": { - "version": "4.17.21", - "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", - "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==" + "node_modules/lodash.includes": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/lodash.includes/-/lodash.includes-4.3.0.tgz", + "integrity": "sha512-W3Bx6mdkRTGtlJISOvVD/lbqjTlPPUDTMnlXZFnVwi9NKJ6tiAk6LVdlhZMm17VZisqhKcgzpO5Wz91PCt5b0w==" + }, + "node_modules/lodash.isboolean": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/lodash.isboolean/-/lodash.isboolean-3.0.3.tgz", + "integrity": "sha512-Bz5mupy2SVbPHURB98VAcw+aHh4vRV5IPNhILUCsOzRmsTmSQ17jIuqopAentWoehktxGd9e/hbIXq980/1QJg==" + }, + "node_modules/lodash.isinteger": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/lodash.isinteger/-/lodash.isinteger-4.0.4.tgz", + "integrity": "sha512-DBwtEWN2caHQ9/imiNeEA5ys1JoRtRfY3d7V9wkqtbycnAmTvRRmbHKDV4a0EYc678/dia0jrte4tjYwVBaZUA==" + }, + "node_modules/lodash.isnumber": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/lodash.isnumber/-/lodash.isnumber-3.0.3.tgz", + "integrity": "sha512-QYqzpfwO3/CWf3XP+Z+tkQsfaLL/EnUlXWVkIk5FUPc4sBdTehEqZONuyRt2P67PXAk+NXmTBcc97zw9t1FQrw==" + }, + "node_modules/lodash.isplainobject": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz", + "integrity": "sha512-oSXzaWypCMHkPC3NvBEaPHf0KsA5mvPrOPgQWDsbg8n7orZ290M0BmC/jgRZ4vcJ6DTAhjrsSYgdsW/F+MFOBA==" + }, + "node_modules/lodash.isstring": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/lodash.isstring/-/lodash.isstring-4.0.1.tgz", + "integrity": "sha512-0wJxfxH1wgO3GrbuP+dTTk7op+6L41QCXbGINEmD+ny/G/eCqGzxyCsh7159S+mgDDcoarnBw6PC1PS5+wUGgw==" + }, + "node_modules/lodash.once": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/lodash.once/-/lodash.once-4.1.1.tgz", + "integrity": "sha512-Sb487aTOCr9drQVL8pIxOzVhafOjZN9UU54hiN8PU3uAiSV7lx1yYNpbNmex2PK6dSJoNTSJUUswT651yww3Mg==" }, "node_modules/lru-cache": { "version": "6.0.0", @@ -2194,9 +2230,9 @@ "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==" }, "node_modules/semver": { - "version": "7.5.3", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.5.3.tgz", - "integrity": "sha512-QBlUtyVk/5EeHbi7X0fw6liDZc7BBmEaSYn01fMU1OUYbf6GPsbTtd8WmnqbI20SeycoHSeiybkE/q1Q+qlThQ==", + "version": "7.5.4", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.5.4.tgz", + "integrity": "sha512-1bCSESV6Pv+i21Hvpxp3Dx+pSD8lIPt8uVjRrxAUt/nbswYc+tK6Y2btiULjd4+fnq15PX+nqQDC7Oft7WkwcA==", "dependencies": { "lru-cache": "^6.0.0" }, diff --git a/package.json b/package.json index 96f75bd..38438aa 100644 --- a/package.json +++ b/package.json @@ -24,7 +24,7 @@ "express-session": "^1.17.3", "fs": "^0.0.1-security", "google-auth-library": "^9.0.0", - "jsonwebtoken": "^9.0.1", + "jsonwebtoken": "^9.0.2", "morgan": "^1.10.0", "nodemailer": "^6.9.4", "nodemon": "^2.0.22", From 88b83195609bb3e6df0ae0c50439219deb0f99fe Mon Sep 17 00:00:00 2001 From: Hussein Bahdon <35459369+H-BAHDON@users.noreply.github.com> Date: Thu, 26 Oct 2023 12:39:38 +0100 Subject: [PATCH 24/33] Updated --- app/controllers/authController.js | 31 ++++++----------------------- app/controllers/googleController.js | 4 ++-- app/routes/authRoutes.js | 11 +--------- config/db/db.js | 5 +---- 4 files changed, 10 insertions(+), 41 deletions(-) diff --git a/app/controllers/authController.js b/app/controllers/authController.js index fde4938..8252876 100644 --- a/app/controllers/authController.js +++ b/app/controllers/authController.js @@ -74,31 +74,12 @@ async function saveScore(req, res) { function getUser(req, res) { if (req.isAuthenticated()) { - const userId = req.user.id; - db.query('SELECT full_name, email FROM users WHERE id = $1', [userId]) - .then(result => { - if (result.rows.length === 0) { - // User not found in the database, use backup method - const userData = { - displayName: req.user.displayName || req.user.username, // Use username if displayName is not available - email: req.user.email, - }; - req.session.userData = userData; - res.json(userData); - } else { - // User found in the database - const userData = { - displayName: result.rows[0].full_name, - email: result.rows[0].email, - }; - req.session.userData = userData; - res.json(userData); - } - }) - .catch(error => { - console.error('Error fetching user data from the database:', error); - res.status(500).json({ error: 'Internal server error' }); - }); + const userData = { + displayName: req.user.displayName || req.user.username, + email: req.user.email, + }; + req.session.userData = userData; + res.json({ message: 'User authenticated', userData }); } else { res.status(401).json({ error: 'Not authenticated' }); } diff --git a/app/controllers/googleController.js b/app/controllers/googleController.js index 7e12843..8ed560b 100644 --- a/app/controllers/googleController.js +++ b/app/controllers/googleController.js @@ -1,6 +1,6 @@ const passport = require("passport"); const jwt = require('jsonwebtoken'); - +const secretKey = 'melly'; function googleAuth(req, res) { passport.authenticate('google', { scope: ['email', 'profile'] })(req, res); } @@ -19,7 +19,7 @@ function googleCallback(req, res, next) { } // Generate a JWT token - const token = jwt.sign(user, process.env.JWT_SECRET, { expiresIn: '24h' }); + const token = jwt.sign(user, secretKey, { expiresIn: '24h' }); // Set the token in an HTTP-only cookie res.cookie('token', token, { diff --git a/app/routes/authRoutes.js b/app/routes/authRoutes.js index 9141088..4bc1575 100644 --- a/app/routes/authRoutes.js +++ b/app/routes/authRoutes.js @@ -11,16 +11,7 @@ router.get('/platform', authController.platform); router.post('/login', authController.login); -router.get('/user', (req, res) => { - const token = generateToken(req.user); - res.cookie('token', token, { - httpOnly: true, - secure: process.env.NODE_ENV === 'production', - maxAge: 24 * 60 * 60 * 1000, - sameSite: 'none', - }); - res.json({ message: 'User authenticated', token }); - }); +router.get('/user', authController.getUser); // router.get('/protected', isLoggedIn, authController.protected); diff --git a/config/db/db.js b/config/db/db.js index 90902c4..434e672 100644 --- a/config/db/db.js +++ b/config/db/db.js @@ -1,6 +1,5 @@ const { Pool } = require('pg'); -// Create a new instance of the Pool class const pool = new Pool({ connectionString: 'postgres://hzxxyodc:lx9EgngCHzM-uAX0GnOpdwrZXX4vsSe5@surus.db.elephantsql.com/hzxxyodc', ssl: { @@ -8,10 +7,8 @@ const pool = new Pool({ } }); -// Test the connection to the database pool.query('SELECT NOW()') .then(res => console.log('Database for users connected! Current time: ', res.rows[0].now)) .catch(err => console.error('Database connection error: ', err.stack)); - -// Export the pool object for use in other modules + module.exports = pool; From 6070be52a848b7a64804ec3de4793a852cf547f6 Mon Sep 17 00:00:00 2001 From: Hussein Bahdon <35459369+H-BAHDON@users.noreply.github.com> Date: Mon, 30 Oct 2023 01:07:27 +0000 Subject: [PATCH 25/33] Updated auth --- app/app.js | 10 +++++++--- app/controllers/authController.js | 21 ++++++++------------- app/controllers/googleController.js | 6 +----- app/controllers/tokens.js | 3 --- app/routes/authRoutes.js | 11 ++++------- 5 files changed, 20 insertions(+), 31 deletions(-) diff --git a/app/app.js b/app/app.js index 809e8b1..744f0fd 100644 --- a/app/app.js +++ b/app/app.js @@ -10,7 +10,7 @@ require('dotenv').config(); const authRoutes = require('../app/routes/authRoutes'); const githubRoutes = require('../app/routes/githubRoutes'); -const googleRoutes = require('../app/routes/googleRoute'); // Replace with the correct path to your Google OAuth route file +const googleRoutes = require('../app/routes/googleRoute'); const GoogleStrategy = require('../Auth/googleStrategy'); @@ -21,6 +21,7 @@ passport.use(GithubStrategy); app.set('view engine', 'ejs'); app.use(cookieParser()); + app.use( cors({ origin: ['https://www.mmcode.io', 'http://localhost:3000'], @@ -46,17 +47,20 @@ app.set('trust proxy', 1); app.use(passport.initialize()); app.use(passport.session()); + + + passport.serializeUser((user, done) => { - // Serialize the user to the session done(null, user); }); passport.deserializeUser((user, done) => { - // Deserialize the user from the session done(null, user); }); + + app.use('/', authRoutes); app.use('/', githubRoutes); app.use('/', googleRoutes); diff --git a/app/controllers/authController.js b/app/controllers/authController.js index 8252876..008c03e 100644 --- a/app/controllers/authController.js +++ b/app/controllers/authController.js @@ -1,5 +1,6 @@ const db = require('../../config/db/db'); -const { verifyToken, generateToken } = require('../controllers/tokens'); // Import your verifyToken function +const { verifyToken, generateToken } = require('../controllers/tokens'); +const passport = require('passport'); function platform(req, res) { req.session.randomValue = Math.random(); @@ -11,23 +12,17 @@ function platform(req, res) { function homePage(req, res) { res.send("Home page running well.") -// query db - // handleScore(req, res); + } async function login(req, res) { try { - // Assuming you have user data from Google OAuth in req.user object const { displayName, email } = req.user; - - // Generate a token - const token = generateToken({ displayName, email }); // Customize this based on your user data - - // Set the token in the response cookie + const token = generateToken({ displayName, email }); res.cookie('token', token, { httpOnly: true, secure: process.env.NODE_ENV === 'production', - maxAge: 24 * 60 * 60 * 1000, // 24 hours expiration + maxAge: 24 * 60 * 60 * 1000, sameSite: 'none', }); @@ -78,6 +73,8 @@ function getUser(req, res) { displayName: req.user.displayName || req.user.username, email: req.user.email, }; + console.log(req.user); + req.session.userData = userData; res.json({ message: 'User authenticated', userData }); } else { @@ -88,7 +85,7 @@ function getUser(req, res) { function checkSession(req, res) { - const token = req.cookies.session; // Assuming the token is stored in a cookie named 'token' + const token = req.cookies.session; if (!token) { return res.status(401).json({ error: 'Unauthorized' }); @@ -97,11 +94,9 @@ function checkSession(req, res) { const decodedToken = verifyToken(token); if (!decodedToken) { - // Invalid or expired token return res.status(401).json({ error: 'Unauthorized' }); } - // Token is valid, user is authenticated return res.status(200).json({ message: 'User is authenticated' }); } diff --git a/app/controllers/googleController.js b/app/controllers/googleController.js index 8ed560b..cc30280 100644 --- a/app/controllers/googleController.js +++ b/app/controllers/googleController.js @@ -14,22 +14,18 @@ function googleCallback(req, res, next) { return next(err); } if (!user) { - // Handle authentication failure return res.redirect(`${process.env.Client_SIDE_BASE_URL}/login`); } - // Generate a JWT token const token = jwt.sign(user, secretKey, { expiresIn: '24h' }); - // Set the token in an HTTP-only cookie res.cookie('token', token, { httpOnly: true, secure: process.env.NODE_ENV === 'production', - maxAge: 24 * 60 * 60 * 1000, // 24 hours expiration + maxAge: 24 * 60 * 60 * 1000, sameSite: 'none', }); - // Redirect to the desired page after successful login return res.redirect(`${process.env.Client_SIDE_BASE_URL}/platform`); })(req, res, next); } diff --git a/app/controllers/tokens.js b/app/controllers/tokens.js index 66d4eb1..7516e3f 100644 --- a/app/controllers/tokens.js +++ b/app/controllers/tokens.js @@ -2,19 +2,16 @@ const jwt = require('jsonwebtoken'); const secretKey = 'melly'; -// Function to generate a JWT token function generateToken(user) { const token = jwt.sign({ user }, secretKey, { expiresIn: '24h' }); return token; } -// Function to verify JWT token function verifyToken(token) { try { const decoded = jwt.verify(token, secretKey); return decoded; } catch (error) { - // Token is invalid or expired return null; } } diff --git a/app/routes/authRoutes.js b/app/routes/authRoutes.js index 4bc1575..37386b0 100644 --- a/app/routes/authRoutes.js +++ b/app/routes/authRoutes.js @@ -1,8 +1,9 @@ const express = require('express'); const router = express.Router(); const authController = require('../controllers/authController'); -// const { isLoggedIn } = require('../middleware/authenticationMiddleware'); -const { generateToken } = require('../controllers/tokens'); // Import your generateToken function +const { generateToken } = require('../controllers/tokens'); +const passport = require('passport'); + router.get('/', authController.homePage) router.get('/score', authController.handleScore) @@ -10,11 +11,7 @@ router.post('/save-score', authController.saveScore); router.get('/platform', authController.platform); router.post('/login', authController.login); - -router.get('/user', authController.getUser); - - - // router.get('/protected', isLoggedIn, authController.protected); +router.get('/user', passport.authenticate(), authController.getUser); router.get('/check-session', authController.checkSession) router.get('/logout', authController.logout); From 8092a30440d23f1619e610339bf25246944452bb Mon Sep 17 00:00:00 2001 From: Hussein Bahdon <35459369+H-BAHDON@users.noreply.github.com> Date: Mon, 30 Oct 2023 01:29:11 +0000 Subject: [PATCH 26/33] Updated --- Auth/googleStrategy.js | 2 +- app/app.js | 8 ++------ app/controllers/authController.js | 6 +++--- config/passport.js | 0 4 files changed, 6 insertions(+), 10 deletions(-) delete mode 100644 config/passport.js diff --git a/Auth/googleStrategy.js b/Auth/googleStrategy.js index e7ae14e..6de55fb 100644 --- a/Auth/googleStrategy.js +++ b/Auth/googleStrategy.js @@ -18,7 +18,7 @@ const googleStrategy = new GoogleStrategy({ if (result.rows.length === 0) { const insertUserQuery = 'INSERT INTO users (full_name, email, accounts) VALUES ($1, $2, $3)'; - const insertUserValues = [profile.displayName, profile.emails[0].value, 'Google']; // Set the account provider to 'Google' + const insertUserValues = [profile.displayName, profile.emails[0].value, 'Google']; db.query(insertUserQuery, insertUserValues, (err) => { if (err) { diff --git a/app/app.js b/app/app.js index 744f0fd..49b0c52 100644 --- a/app/app.js +++ b/app/app.js @@ -21,7 +21,6 @@ passport.use(GithubStrategy); app.set('view engine', 'ejs'); app.use(cookieParser()); - app.use( cors({ origin: ['https://www.mmcode.io', 'http://localhost:3000'], @@ -47,20 +46,17 @@ app.set('trust proxy', 1); app.use(passport.initialize()); app.use(passport.session()); - - - passport.serializeUser((user, done) => { + // Serialize the user to the session done(null, user); }); passport.deserializeUser((user, done) => { + // Deserialize the user from the session done(null, user); }); - - app.use('/', authRoutes); app.use('/', githubRoutes); app.use('/', googleRoutes); diff --git a/app/controllers/authController.js b/app/controllers/authController.js index 008c03e..1ce0bbd 100644 --- a/app/controllers/authController.js +++ b/app/controllers/authController.js @@ -1,6 +1,5 @@ const db = require('../../config/db/db'); const { verifyToken, generateToken } = require('../controllers/tokens'); -const passport = require('passport'); function platform(req, res) { req.session.randomValue = Math.random(); @@ -69,11 +68,12 @@ async function saveScore(req, res) { function getUser(req, res) { if (req.isAuthenticated()) { + console.log(req.user); + const userData = { - displayName: req.user.displayName || req.user.username, + displayName: req.user.displayName || req.user.username || req.user.fullName, email: req.user.email, }; - console.log(req.user); req.session.userData = userData; res.json({ message: 'User authenticated', userData }); diff --git a/config/passport.js b/config/passport.js deleted file mode 100644 index e69de29..0000000 From 6618c0b057f2fe0d70df22574f466e1f7becd141 Mon Sep 17 00:00:00 2001 From: Hussein Bahdon <35459369+H-BAHDON@users.noreply.github.com> Date: Wed, 1 Nov 2023 14:12:52 +0000 Subject: [PATCH 27/33] Updated the token --- .env | 2 +- Auth/googleStrategy.js | 21 ++++++- app/app.js | 28 ++++++--- app/controllers/authController.js | 96 +++++++++++-------------------- app/controllers/tokens.js | 15 +++-- app/routes/authRoutes.js | 34 ++++++++--- app/routes/googleRoute.js | 4 +- 7 files changed, 114 insertions(+), 86 deletions(-) diff --git a/.env b/.env index b09049d..5af7235 100644 --- a/.env +++ b/.env @@ -13,7 +13,7 @@ REACT_APP_SECRET_KEY=abcdef123456 Client_SIDE_BASE_URL="http://localhost:3000" # Client_SIDE_BASE_URL=https://www.mmcode.io -GOOGLE_CLIENT_SECRET="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" +GOOGLE_CLIENT_SECRET="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" GOOGLE_CLIENT_ID="617409105699-u5senri6ujm3b655n5gkb0g6f7r8r5j1.apps.googleusercontent.com" GITHUB_CLIENT_ID="613427a2df3476638f43" diff --git a/Auth/googleStrategy.js b/Auth/googleStrategy.js index 6de55fb..21df72a 100644 --- a/Auth/googleStrategy.js +++ b/Auth/googleStrategy.js @@ -1,10 +1,15 @@ const GoogleStrategy = require('passport-google-oauth20').Strategy; const db = require('../config/db/db'); // Import your database configuration +const passport = require('passport'); + +const GOOGLE_CLIENT_SECRET="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" +const GOOGLE_CLIENT_ID="617409105699-u5senri6ujm3b655n5gkb0g6f7r8r5j1.apps.googleusercontent.com" + const googleStrategy = new GoogleStrategy({ - clientID: process.env.GOOGLE_CLIENT_ID, - clientSecret: process.env.GOOGLE_CLIENT_SECRET, - callbackURL: `${process.env.REACT_APP_API_URL}/auth/google/callback`, + clientID: GOOGLE_CLIENT_ID, + clientSecret: GOOGLE_CLIENT_SECRET, + callbackURL: `http://localhost:3001/auth/google/callback`, passReqToCallback: true, }, function (request, accessToken, refreshToken, profile, done) { @@ -43,5 +48,15 @@ const googleStrategy = new GoogleStrategy({ }); }); +passport.serializeUser(function(user, done) { + done(null, user); +}); + +passport.deserializeUser(function(id, done) { + // Query your database using the provided user ID + User.findById(id, function(err, user) { + done(err, user); + }); +}); module.exports = googleStrategy; diff --git a/app/app.js b/app/app.js index 49b0c52..4144477 100644 --- a/app/app.js +++ b/app/app.js @@ -7,23 +7,22 @@ const passport = require('passport'); const morgan = require('morgan'); const bodyParser = require('body-parser'); require('dotenv').config(); +const session = require('express-session'); const authRoutes = require('../app/routes/authRoutes'); const githubRoutes = require('../app/routes/githubRoutes'); const googleRoutes = require('../app/routes/googleRoute'); - const GoogleStrategy = require('../Auth/googleStrategy'); const GithubStrategy = require('../Auth/githubStrategy'); passport.use(GoogleStrategy); - passport.use(GithubStrategy); app.set('view engine', 'ejs'); app.use(cookieParser()); app.use( cors({ - origin: ['https://www.mmcode.io', 'http://localhost:3000'], + origin: ['http://localhost:3000'], methods: ['GET', 'POST'], credentials: true, }) @@ -42,22 +41,33 @@ app.use( secure: true, }) ); + app.set('trust proxy', 1); + + app.use(passport.initialize()); app.use(passport.session()); -passport.serializeUser((user, done) => { - // Serialize the user to the session +passport.serializeUser(function(user, done) { + // Store user information in session done(null, user); }); -passport.deserializeUser((user, done) => { - // Deserialize the user from the session - done(null, user); +passport.deserializeUser(function(id, done) { + // Query your database using the provided user ID + User.findById(id, function(err, user) { + done(err, user); + }); }); - +// Define routes app.use('/', authRoutes); app.use('/', githubRoutes); app.use('/', googleRoutes); + +app.use((err, req, res, next) => { + console.error(err.stack); + res.status(500).send('Something went wrong!'); +}); + module.exports = app; diff --git a/app/controllers/authController.js b/app/controllers/authController.js index 1ce0bbd..19dab5d 100644 --- a/app/controllers/authController.js +++ b/app/controllers/authController.js @@ -1,6 +1,7 @@ const db = require('../../config/db/db'); const { verifyToken, generateToken } = require('../controllers/tokens'); - +const jwt = require('jsonwebtoken'); +const secretKey = 'melly'; function platform(req, res) { req.session.randomValue = Math.random(); const storedRandomValue = req.session.randomValue; @@ -16,89 +17,65 @@ function homePage(req, res) { async function login(req, res) { try { - const { displayName, email } = req.user; - const token = generateToken({ displayName, email }); - res.cookie('token', token, { - httpOnly: true, - secure: process.env.NODE_ENV === 'production', - maxAge: 24 * 60 * 60 * 1000, - sameSite: 'none', - }); - - res.json({ message: 'User authenticated', token }); - } catch (error) { - console.error('Error authenticating user:', error); - res.status(500).json({ error: 'Internal server error' }); - } -} - + // Authenticate the user, validate credentials, etc. + const { username, password } = req.body; -async function handleScore(req, res) { - try { - } catch (error) { - console.error('Error handling score:', error); - res.status(500).json({ error: 'Error handling score' }); - } -} - -async function saveScore(req, res) { - try { - const { score } = req.body; + // Check user credentials (this is just an example, replace it with your authentication logic) + if (username === 'user' && password === 'password') { + // Generate a JSON web token (JWT) for the authenticated user + const token = jwt.sign({ username }, secretKey, { expiresIn: '24h' }); - if (!req.isAuthenticated()) { - return res.status(401).json({ error: 'Not authenticated' }); - } - const userEmail = req.user.email; - - if (!isNaN(score)) { - const query = 'UPDATE users SET total_score = total_score + $1 WHERE email = $2'; - await db.query(query, [score, userEmail]); - console.log('Score saved successfully'); - res.json({ message: 'Score saved successfully' }); + // Send the token to the client + res.json({ message: 'User authenticated', token }); } else { - console.log('Invalid score value'); - res.status(400).json({ error: 'Invalid score value' }); + // If authentication fails, send an error response + res.status(401).json({ error: 'Invalid credentials' }); } } catch (error) { - console.error('Error saving score:', error); - res.status(500).json({ error: 'Error saving score' }); + // Handle errors, log them, and send an error response + console.error('Error authenticating user:', error); + res.status(500).json({ error: 'Internal server error' }); } } + function getUser(req, res) { - if (req.isAuthenticated()) { - console.log(req.user); + console.log('Session:', req.session); // Log session information + console.log('Authenticated:', req.isAuthenticated()); // Log if the user is authenticated + console.log('User:', req.user); // Log the user object from the request - const userData = { + if (req.isAuthenticated()) { + console.log('Authenticated User:', req.user); + const userData = { displayName: req.user.displayName || req.user.username || req.user.fullName, email: req.user.email, }; - - req.session.userData = userData; res.json({ message: 'User authenticated', userData }); } else { + console.error('Authentication Error:', req.user); res.status(401).json({ error: 'Not authenticated' }); } } -function checkSession(req, res) { - const token = req.cookies.session; - if (!token) { - return res.status(401).json({ error: 'Unauthorized' }); - } +// function checkSession(req, res) { +// const token = req.cookies.session; - const decodedToken = verifyToken(token); +// if (!token) { +// return res.status(401).json({ error: 'Unauthorized' }); +// } - if (!decodedToken) { - return res.status(401).json({ error: 'Unauthorized' }); - } +// const decodedToken = verifyToken(token); - return res.status(200).json({ message: 'User is authenticated' }); -} +// if (!decodedToken) { +// return res.status(401).json({ error: 'Unauthorized' }); +// } + +// return res.status(200).json({ message: 'User is authenticated' }); +// } function logout(req, res) { @@ -110,9 +87,6 @@ module.exports = { homePage, platform, getUser, - checkSession, logout, - handleScore, - saveScore, login }; diff --git a/app/controllers/tokens.js b/app/controllers/tokens.js index 7516e3f..915f0d3 100644 --- a/app/controllers/tokens.js +++ b/app/controllers/tokens.js @@ -7,12 +7,19 @@ function generateToken(user) { return token; } -function verifyToken(token) { +function verifyToken(req, res, next) { + const token = req.header('Authorization'); + + if (!token) { + return res.status(401).json({ error: 'Access denied. No token provided.' }); + } + try { - const decoded = jwt.verify(token, secretKey); - return decoded; + const decoded = jwt.verify(token, secretKey); // Replace 'your-secret-key' with your actual secret key used for signing the token + req.user = decoded; // The decoded payload is available in req.user + next(); } catch (error) { - return null; + return res.status(403).json({ error: 'Invalid token.' }); } } diff --git a/app/routes/authRoutes.js b/app/routes/authRoutes.js index 37386b0..f37da6b 100644 --- a/app/routes/authRoutes.js +++ b/app/routes/authRoutes.js @@ -1,19 +1,39 @@ const express = require('express'); const router = express.Router(); const authController = require('../controllers/authController'); -const { generateToken } = require('../controllers/tokens'); -const passport = require('passport'); +const jwt = require('jsonwebtoken'); +const secretKey = 'melly'; +router.get('/', authController.homePage); -router.get('/', authController.homePage) -router.get('/score', authController.handleScore) -router.post('/save-score', authController.saveScore); router.get('/platform', authController.platform); router.post('/login', authController.login); -router.get('/user', passport.authenticate(), authController.getUser); +router.get('/user', (req, res) => { + // Access the token from the cookie + const token = req.cookies.token; + + if (!token) { + return res.status(401).json({ error: 'Unauthorized' }); + } + + try { + // Verify the token + const decoded = jwt.verify(token, secretKey); + + // User is authenticated, you can access user data from decoded payload + const userData = { + displayName: decoded.displayName || decoded.username || decoded.fullName, + email: decoded.email, + }; + + res.json({ message: 'User authenticated', userData }); + } catch (error) { + console.error('Authentication Error:', error); + res.status(401).json({ error: 'Unauthorized' }); + } +}); -router.get('/check-session', authController.checkSession) router.get('/logout', authController.logout); module.exports = router; diff --git a/app/routes/googleRoute.js b/app/routes/googleRoute.js index 1cbd2ac..f366a27 100644 --- a/app/routes/googleRoute.js +++ b/app/routes/googleRoute.js @@ -2,9 +2,11 @@ const express = require('express'); const router = express.Router(); const googleController = require('../controllers/googleController'); const authenticationMiddleware = require('../middleware/authenticationMiddleware'); +const passport = require('passport'); router.get('/auth/google', googleController.googleAuth); router.get('/auth/google/callback', googleController.googleCallback); -router.get('/auth/google/failure', authenticationMiddleware.isLoggedIn, googleController.googleFailure); +router.get('/auth/google/failure', googleController.googleFailure); module.exports = router; + \ No newline at end of file From 700ec5bc95c5579ec6ad33c1e3802b37c9fa5fc4 Mon Sep 17 00:00:00 2001 From: Hussein Bahdon <35459369+H-BAHDON@users.noreply.github.com> Date: Thu, 2 Nov 2023 15:51:51 +0000 Subject: [PATCH 28/33] Updated authController.js --- app/controllers/authController.js | 1 + 1 file changed, 1 insertion(+) diff --git a/app/controllers/authController.js b/app/controllers/authController.js index 19dab5d..27d1f43 100644 --- a/app/controllers/authController.js +++ b/app/controllers/authController.js @@ -79,6 +79,7 @@ function getUser(req, res) { function logout(req, res) { + res.clearCookie('token'); req.logout(); res.status(200).json({ success : true }); } From 95956fb0de0834da8379d14e8afc940e1366e16d Mon Sep 17 00:00:00 2001 From: Hussein Bahdon <35459369+H-BAHDON@users.noreply.github.com> Date: Thu, 2 Nov 2023 16:05:11 +0000 Subject: [PATCH 29/33] Updated secret --- .env | 4 +++- app/controllers/authController.js | 2 +- app/controllers/googleController.js | 3 ++- app/controllers/tokens.js | 6 +++--- app/routes/authRoutes.js | 4 ++-- 5 files changed, 11 insertions(+), 8 deletions(-) diff --git a/.env b/.env index 5af7235..6aeabba 100644 --- a/.env +++ b/.env @@ -17,4 +17,6 @@ GOOGLE_CLIENT_SECRET="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" GOOGLE_CLIENT_ID="617409105699-u5senri6ujm3b655n5gkb0g6f7r8r5j1.apps.googleusercontent.com" GITHUB_CLIENT_ID="613427a2df3476638f43" -GITHUB_CLIENT_SECRET="417c54c316a47b3ead02087f71bce99b75c856bf" \ No newline at end of file +GITHUB_CLIENT_SECRET="417c54c316a47b3ead02087f71bce99b75c856bf" + +SECRET_KEY=melly diff --git a/app/controllers/authController.js b/app/controllers/authController.js index 27d1f43..e9ba8f9 100644 --- a/app/controllers/authController.js +++ b/app/controllers/authController.js @@ -1,7 +1,7 @@ const db = require('../../config/db/db'); const { verifyToken, generateToken } = require('../controllers/tokens'); const jwt = require('jsonwebtoken'); -const secretKey = 'melly'; +const secretKey = process.env.SECRET_KEY; function platform(req, res) { req.session.randomValue = Math.random(); const storedRandomValue = req.session.randomValue; diff --git a/app/controllers/googleController.js b/app/controllers/googleController.js index cc30280..1882bd1 100644 --- a/app/controllers/googleController.js +++ b/app/controllers/googleController.js @@ -1,6 +1,7 @@ const passport = require("passport"); const jwt = require('jsonwebtoken'); -const secretKey = 'melly'; +const secretKey = process.env.SECRET_KEY; + function googleAuth(req, res) { passport.authenticate('google', { scope: ['email', 'profile'] })(req, res); } diff --git a/app/controllers/tokens.js b/app/controllers/tokens.js index 915f0d3..bf5d77f 100644 --- a/app/controllers/tokens.js +++ b/app/controllers/tokens.js @@ -1,6 +1,6 @@ const jwt = require('jsonwebtoken'); -const secretKey = 'melly'; +const secretKey = process.env.SECRET_KEY; function generateToken(user) { const token = jwt.sign({ user }, secretKey, { expiresIn: '24h' }); @@ -15,8 +15,8 @@ function verifyToken(req, res, next) { } try { - const decoded = jwt.verify(token, secretKey); // Replace 'your-secret-key' with your actual secret key used for signing the token - req.user = decoded; // The decoded payload is available in req.user + const decoded = jwt.verify(token, secretKey); + req.user = decoded; next(); } catch (error) { return res.status(403).json({ error: 'Invalid token.' }); diff --git a/app/routes/authRoutes.js b/app/routes/authRoutes.js index f37da6b..bbc7e4b 100644 --- a/app/routes/authRoutes.js +++ b/app/routes/authRoutes.js @@ -2,7 +2,7 @@ const express = require('express'); const router = express.Router(); const authController = require('../controllers/authController'); const jwt = require('jsonwebtoken'); -const secretKey = 'melly'; +const secretKey = process.env.SECRET_KEY; router.get('/', authController.homePage); @@ -19,7 +19,7 @@ router.get('/user', (req, res) => { try { // Verify the token - const decoded = jwt.verify(token, secretKey); + const decoded = jwt.verify(token, secretKey ); // User is authenticated, you can access user data from decoded payload const userData = { From ba1a1eb78a681ef6272a2a139e5c945d29d7110c Mon Sep 17 00:00:00 2001 From: Hussein Bahdon <35459369+H-BAHDON@users.noreply.github.com> Date: Thu, 2 Nov 2023 16:14:07 +0000 Subject: [PATCH 30/33] Updated --- Auth/googleStrategy.js | 19 ++++--------------- app/app.js | 5 +---- app/controllers/authController.js | 16 +++++----------- app/routes/authRoutes.js | 4 ---- 4 files changed, 10 insertions(+), 34 deletions(-) diff --git a/Auth/googleStrategy.js b/Auth/googleStrategy.js index 21df72a..58dd9dd 100644 --- a/Auth/googleStrategy.js +++ b/Auth/googleStrategy.js @@ -2,14 +2,13 @@ const GoogleStrategy = require('passport-google-oauth20').Strategy; const db = require('../config/db/db'); // Import your database configuration const passport = require('passport'); -const GOOGLE_CLIENT_SECRET="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" -const GOOGLE_CLIENT_ID="617409105699-u5senri6ujm3b655n5gkb0g6f7r8r5j1.apps.googleusercontent.com" + const googleStrategy = new GoogleStrategy({ - clientID: GOOGLE_CLIENT_ID, - clientSecret: GOOGLE_CLIENT_SECRET, - callbackURL: `http://localhost:3001/auth/google/callback`, + clientID: process.env.GOOGLE_CLIENT_ID, + clientSecret: process.env.GOOGLE_CLIENT_SECRET, + callbackURL: `${process.env.REACT_APP_API_URL}/auth/google/callback`, passReqToCallback: true, }, function (request, accessToken, refreshToken, profile, done) { @@ -48,15 +47,5 @@ const googleStrategy = new GoogleStrategy({ }); }); -passport.serializeUser(function(user, done) { - done(null, user); -}); - -passport.deserializeUser(function(id, done) { - // Query your database using the provided user ID - User.findById(id, function(err, user) { - done(err, user); - }); -}); module.exports = googleStrategy; diff --git a/app/app.js b/app/app.js index 4144477..a31b3a7 100644 --- a/app/app.js +++ b/app/app.js @@ -22,7 +22,7 @@ app.set('view engine', 'ejs'); app.use(cookieParser()); app.use( cors({ - origin: ['http://localhost:3000'], + origin: [process.env.CLIENT_SIDE_BASE_URL], methods: ['GET', 'POST'], credentials: true, }) @@ -49,18 +49,15 @@ app.use(passport.initialize()); app.use(passport.session()); passport.serializeUser(function(user, done) { - // Store user information in session done(null, user); }); passport.deserializeUser(function(id, done) { - // Query your database using the provided user ID User.findById(id, function(err, user) { done(err, user); }); }); -// Define routes app.use('/', authRoutes); app.use('/', githubRoutes); app.use('/', googleRoutes); diff --git a/app/controllers/authController.js b/app/controllers/authController.js index e9ba8f9..647d8f0 100644 --- a/app/controllers/authController.js +++ b/app/controllers/authController.js @@ -1,7 +1,7 @@ -const db = require('../../config/db/db'); -const { verifyToken, generateToken } = require('../controllers/tokens'); const jwt = require('jsonwebtoken'); const secretKey = process.env.SECRET_KEY; + + function platform(req, res) { req.session.randomValue = Math.random(); const storedRandomValue = req.session.randomValue; @@ -17,22 +17,16 @@ function homePage(req, res) { async function login(req, res) { try { - // Authenticate the user, validate credentials, etc. const { username, password } = req.body; - // Check user credentials (this is just an example, replace it with your authentication logic) if (username === 'user' && password === 'password') { - // Generate a JSON web token (JWT) for the authenticated user const token = jwt.sign({ username }, secretKey, { expiresIn: '24h' }); - // Send the token to the client res.json({ message: 'User authenticated', token }); } else { - // If authentication fails, send an error response res.status(401).json({ error: 'Invalid credentials' }); } } catch (error) { - // Handle errors, log them, and send an error response console.error('Error authenticating user:', error); res.status(500).json({ error: 'Internal server error' }); } @@ -41,9 +35,9 @@ async function login(req, res) { function getUser(req, res) { - console.log('Session:', req.session); // Log session information - console.log('Authenticated:', req.isAuthenticated()); // Log if the user is authenticated - console.log('User:', req.user); // Log the user object from the request + console.log('Session:', req.session); + console.log('Authenticated:', req.isAuthenticated()); + console.log('User:', req.user); if (req.isAuthenticated()) { console.log('Authenticated User:', req.user); diff --git a/app/routes/authRoutes.js b/app/routes/authRoutes.js index bbc7e4b..c0becd0 100644 --- a/app/routes/authRoutes.js +++ b/app/routes/authRoutes.js @@ -10,7 +10,6 @@ router.get('/platform', authController.platform); router.post('/login', authController.login); router.get('/user', (req, res) => { - // Access the token from the cookie const token = req.cookies.token; if (!token) { @@ -18,10 +17,7 @@ router.get('/user', (req, res) => { } try { - // Verify the token const decoded = jwt.verify(token, secretKey ); - - // User is authenticated, you can access user data from decoded payload const userData = { displayName: decoded.displayName || decoded.username || decoded.fullName, email: decoded.email, From 0e150ab2b06bf02ae958da528efc9b5bfdf752b7 Mon Sep 17 00:00:00 2001 From: Hussein Bahdon <35459369+H-BAHDON@users.noreply.github.com> Date: Sat, 4 Nov 2023 15:01:52 +0000 Subject: [PATCH 31/33] Updated login flow --- Auth/auth.js | 6 ++-- app/controllers/authController.js | 57 ------------------------------- app/routes/authRoutes.js | 19 ++++++++++- 3 files changed, 20 insertions(+), 62 deletions(-) diff --git a/Auth/auth.js b/Auth/auth.js index 81b507c..29e4b08 100644 --- a/Auth/auth.js +++ b/Auth/auth.js @@ -1,8 +1,7 @@ const passport = require('passport'); -const GoogleStrategy = require('./googleStrategy'); // Import the exported Google strategy -const githubStrategy = require('./githubStrategy'); // Import the exported GitHub strategy +const GoogleStrategy = require('./googleStrategy'); +const githubStrategy = require('./githubStrategy'); -// Use the Google and GitHub strategies with their respective names passport.use('google', GoogleStrategy); passport.use('github', githubStrategy); @@ -15,5 +14,4 @@ passport.serializeUser(function(user, done) { passport.deserializeUser(function(user, done) { done(null, user); }); -// Export the configured passport module.exports = passport; diff --git a/app/controllers/authController.js b/app/controllers/authController.js index 647d8f0..c300b56 100644 --- a/app/controllers/authController.js +++ b/app/controllers/authController.js @@ -1,6 +1,3 @@ -const jwt = require('jsonwebtoken'); -const secretKey = process.env.SECRET_KEY; - function platform(req, res) { req.session.randomValue = Math.random(); @@ -15,61 +12,9 @@ function homePage(req, res) { } -async function login(req, res) { - try { - const { username, password } = req.body; - - if (username === 'user' && password === 'password') { - const token = jwt.sign({ username }, secretKey, { expiresIn: '24h' }); - - res.json({ message: 'User authenticated', token }); - } else { - res.status(401).json({ error: 'Invalid credentials' }); - } - } catch (error) { - console.error('Error authenticating user:', error); - res.status(500).json({ error: 'Internal server error' }); - } -} - - - -function getUser(req, res) { - console.log('Session:', req.session); - console.log('Authenticated:', req.isAuthenticated()); - console.log('User:', req.user); - - if (req.isAuthenticated()) { - console.log('Authenticated User:', req.user); - const userData = { - displayName: req.user.displayName || req.user.username || req.user.fullName, - email: req.user.email, - }; - res.json({ message: 'User authenticated', userData }); - } else { - console.error('Authentication Error:', req.user); - res.status(401).json({ error: 'Not authenticated' }); - } -} - - - - -// function checkSession(req, res) { -// const token = req.cookies.session; - -// if (!token) { -// return res.status(401).json({ error: 'Unauthorized' }); -// } -// const decodedToken = verifyToken(token); -// if (!decodedToken) { -// return res.status(401).json({ error: 'Unauthorized' }); -// } -// return res.status(200).json({ message: 'User is authenticated' }); -// } function logout(req, res) { @@ -81,7 +26,5 @@ function logout(req, res) { module.exports = { homePage, platform, - getUser, logout, - login }; diff --git a/app/routes/authRoutes.js b/app/routes/authRoutes.js index c0becd0..92ffe1c 100644 --- a/app/routes/authRoutes.js +++ b/app/routes/authRoutes.js @@ -7,7 +7,6 @@ const secretKey = process.env.SECRET_KEY; router.get('/', authController.homePage); router.get('/platform', authController.platform); -router.post('/login', authController.login); router.get('/user', (req, res) => { const token = req.cookies.token; @@ -30,6 +29,24 @@ router.get('/user', (req, res) => { } }); +router.get('/checkSession', (req, res) => { + const token = req.cookies.token; + + if (!token) { + return res.status(401).json({ error: 'Unauthorized' }); + } + + const decodedToken = jwt.verify(token, secretKey ); + + if (!decodedToken) { + return res.status(401).json({ error: 'Unauthorized' }); + } + + return res.status(200).json({ message: 'User is authenticated' }); +}) + router.get('/logout', authController.logout); module.exports = router; + + From 4f519072cdd8056de54ae3fe9c587e7a74ec8329 Mon Sep 17 00:00:00 2001 From: Hussein Bahdon <35459369+H-BAHDON@users.noreply.github.com> Date: Sat, 4 Nov 2023 15:12:40 +0000 Subject: [PATCH 32/33] Updated app.js --- app/app.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/app.js b/app/app.js index a31b3a7..68f4074 100644 --- a/app/app.js +++ b/app/app.js @@ -22,7 +22,7 @@ app.set('view engine', 'ejs'); app.use(cookieParser()); app.use( cors({ - origin: [process.env.CLIENT_SIDE_BASE_URL], + origin: ["https://www.mmcode.io"], methods: ['GET', 'POST'], credentials: true, }) From 95e470448515efe894297f9e0f021ec64ddc87b1 Mon Sep 17 00:00:00 2001 From: Hussein Bahdon Date: Wed, 10 Jan 2024 00:52:46 +0000 Subject: [PATCH 33/33] "Updated env files" --- node_modules/.package-lock.json | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/node_modules/.package-lock.json b/node_modules/.package-lock.json index 393fde0..99bccbb 100644 --- a/node_modules/.package-lock.json +++ b/node_modules/.package-lock.json @@ -935,6 +935,19 @@ "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", "integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==" }, + "node_modules/fsevents": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz", + "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==", + "hasInstallScript": true, + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, "node_modules/function-bind": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz",