From 31a22703c18f7e94bcdf344f55759a14f766acc2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=ADctor=20Losada=20Hern=C3=A1ndez?= Date: Sun, 8 Dec 2024 12:05:01 +0100 Subject: [PATCH 01/17] initial commit --- server/app.js | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/server/app.js b/server/app.js index 8a2e17bbd..fab56e624 100644 --- a/server/app.js +++ b/server/app.js @@ -312,6 +312,34 @@ app.get('/user/:username', async (req, res, next)=>{ return next(); }); +//Rename Brews +app.put('/user/:username/rename-brews', async (req, res) => { + const { username } = req.params; + const { newUsername } = req.body; + + if (!username || !newUsername) { + return res.status(400).json({ error: 'Username and newUsername are required.' }); + } + try { + const brews = await HomebrewModel.getByUser(username, true, ['authors']); + const renamePromises = brews.map(async (brew) => { + const updatedAuthors = brew.authors.map((author) => + author === username ? newUsername : author + ); + return HomebrewModel.updateOne( + { _id: brew._id }, + { $set: { authors: updatedAuthors } } + ); + }); + await Promise.all(renamePromises); + + return res.json({ success: true, message: `Brews for ${username} renamed to ${newUsername}.` }); + } catch (error) { + console.error('Error renaming brews:', error); + return res.status(500).json({ error: 'Failed to rename brews.' }); + } +}); + //Edit Page app.get('/edit/:id', asyncHandler(getBrew('edit')), asyncHandler(async(req, res, next)=>{ req.brew = req.brew.toObject ? req.brew.toObject() : req.brew; From db9212bd12a9837b7882cc1006d6b0b353a96f58 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=ADctor=20Losada=20Hern=C3=A1ndez?= Date: Sun, 8 Dec 2024 20:45:43 +0100 Subject: [PATCH 02/17] log req --- server/middleware/check-client-version.js | 3 +++ 1 file changed, 3 insertions(+) diff --git a/server/middleware/check-client-version.js b/server/middleware/check-client-version.js index 001995f4e..e72a7fd0b 100644 --- a/server/middleware/check-client-version.js +++ b/server/middleware/check-client-version.js @@ -2,6 +2,9 @@ import packageJSON from '../../package.json' with { type: "json" }; const version = packageJSON.version; export default (req, res, next)=>{ + console.log(req); + //check if req comes from localhost + const userVersion = req.get('Homebrewery-Version'); if(userVersion != version) { From 1b20c008425271897ae81be4da9616705062a4f3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=ADctor=20Losada=20Hern=C3=A1ndez?= Date: Sun, 8 Dec 2024 20:46:02 +0100 Subject: [PATCH 03/17] log headers --- server/middleware/check-client-version.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server/middleware/check-client-version.js b/server/middleware/check-client-version.js index e72a7fd0b..3cd30582e 100644 --- a/server/middleware/check-client-version.js +++ b/server/middleware/check-client-version.js @@ -2,7 +2,7 @@ import packageJSON from '../../package.json' with { type: "json" }; const version = packageJSON.version; export default (req, res, next)=>{ - console.log(req); + console.log(req.headers); //check if req comes from localhost const userVersion = req.get('Homebrewery-Version'); From ef0ee787583a27748a47c03f149c262f86dbb75a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=ADctor=20Losada=20Hern=C3=A1ndez?= Date: Sun, 8 Dec 2024 23:43:06 +0100 Subject: [PATCH 04/17] revert check client version changes --- server/middleware/check-client-version.js | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/server/middleware/check-client-version.js b/server/middleware/check-client-version.js index 3cd30582e..19cb40b25 100644 --- a/server/middleware/check-client-version.js +++ b/server/middleware/check-client-version.js @@ -1,10 +1,9 @@ import packageJSON from '../../package.json' with { type: "json" }; const version = packageJSON.version; +//This should be only for internal calls, but right now prevents spam api calls, this should be done with a proper cors policy + export default (req, res, next)=>{ - console.log(req.headers); - //check if req comes from localhost - const userVersion = req.get('Homebrewery-Version'); if(userVersion != version) { From 23910cc94c6002696b436b13c5c332abf6408422 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=ADctor=20Losada=20Hern=C3=A1ndez?= Date: Sun, 8 Dec 2024 23:43:32 +0100 Subject: [PATCH 05/17] add cors policy and rename route --- package-lock.json | 14 ++++++++++++++ package.json | 1 + server/app.js | 47 ++++++++++++++++++++++++++++++++++++++--------- 3 files changed, 53 insertions(+), 9 deletions(-) diff --git a/package-lock.json b/package-lock.json index 820e01c46..bcff9a861 100644 --- a/package-lock.json +++ b/package-lock.json @@ -19,6 +19,7 @@ "classnames": "^2.5.1", "codemirror": "^5.65.6", "cookie-parser": "^1.4.7", + "cors": "^2.8.5", "create-react-class": "^15.7.0", "dedent-tabs": "^0.10.3", "dompurify": "^3.2.2", @@ -4805,6 +4806,19 @@ "integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==", "license": "MIT" }, + "node_modules/cors": { + "version": "2.8.5", + "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.5.tgz", + "integrity": "sha512-KIHbLJqu73RGr/hnbrO9uBeixNGuvSQjul/jdFvS/KFSIH1hWVd1ng7zOHx+YrEfInLG7q4n6GHQ9cDtxv/P6g==", + "license": "MIT", + "dependencies": { + "object-assign": "^4", + "vary": "^1" + }, + "engines": { + "node": ">= 0.10" + } + }, "node_modules/cosmiconfig": { "version": "9.0.0", "resolved": "https://registry.npmjs.org/cosmiconfig/-/cosmiconfig-9.0.0.tgz", diff --git a/package.json b/package.json index d5ea0b1de..2fa8bce4a 100644 --- a/package.json +++ b/package.json @@ -91,6 +91,7 @@ "classnames": "^2.5.1", "codemirror": "^5.65.6", "cookie-parser": "^1.4.7", + "cors": "^2.8.5", "create-react-class": "^15.7.0", "dedent-tabs": "^0.10.3", "dompurify": "^3.2.2", diff --git a/server/app.js b/server/app.js index fab56e624..4ec6ecdff 100644 --- a/server/app.js +++ b/server/app.js @@ -55,6 +55,31 @@ app.use(bodyParser.json({ limit: '25mb' })); app.use(cookieParser()); app.use(forceSSL); +import cors from 'cors'; + +// CORS Configuration +const corsOptions = { + + origin: (origin, callback) => { + const allowedOrigins = [ + 'https://homebrewery.naturalcrit.com', + 'http://localhost:8000', + 'http://localhost:8010', + 'https://naturalcrit.com' + ]; //allow natcrit local and live to call + if (!origin || allowedOrigins.includes(origin)) { + callback(null, true); + } else { + console.log(origin, 'not allowed'); + callback(new Error('Not allowed by CORS')); + } + }, + methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'], + credentials: true, +}; + +app.use(cors(corsOptions)); + //Account Middleware app.use((req, res, next)=>{ if(req.cookies && req.cookies.nc_session){ @@ -313,9 +338,10 @@ app.get('/user/:username', async (req, res, next)=>{ }); //Rename Brews -app.put('/user/:username/rename-brews', async (req, res) => { - const { username } = req.params; - const { newUsername } = req.body; +app.put('/api/user/rename', async (req, res) => { + const { username, newUsername } = req.body; + + console.log('renaming'); if (!username || !newUsername) { return res.status(400).json({ error: 'Username and newUsername are required.' }); @@ -504,12 +530,15 @@ app.get('/vault', asyncHandler(async(req, res, next)=>{ })); //Send rendered page -app.use(asyncHandler(async (req, res, next)=>{ - if (!req.route) return res.redirect('/'); // Catch-all for invalid routes - - const page = await renderPage(req, res); - if(!page) return; - res.send(page); +app.use(asyncHandler(async (req, res, next) => { + if (!req.route && !req.path.startsWith('/api/')) { + return res.redirect('/'); + } + + const page = await renderPage(req, res); + if (!page) return; + + res.send(page); })); //Render the page From 4eb8abf1e7fdb5351261eccd404899138fa31ac9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=ADctor=20Losada=20Hern=C3=A1ndez?= Date: Sun, 8 Dec 2024 23:46:27 +0100 Subject: [PATCH 06/17] `Update CORS error message in app.js` --- server/app.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server/app.js b/server/app.js index 4ec6ecdff..46aabc088 100644 --- a/server/app.js +++ b/server/app.js @@ -71,7 +71,7 @@ const corsOptions = { callback(null, true); } else { console.log(origin, 'not allowed'); - callback(new Error('Not allowed by CORS')); + callback(new Error('Not allowed by CORS, if you think this is an error, please contact us')); } }, methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'], From 81f56ec91d864c73b41ed797869ac15f939d070d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=ADctor=20Losada=20Hern=C3=A1ndez?= Date: Mon, 9 Dec 2024 18:59:48 +0100 Subject: [PATCH 07/17] add heroku apps to cors --- server/app.js | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/server/app.js b/server/app.js index 46aabc088..de44f0609 100644 --- a/server/app.js +++ b/server/app.js @@ -59,18 +59,20 @@ import cors from 'cors'; // CORS Configuration const corsOptions = { - origin: (origin, callback) => { const allowedOrigins = [ - 'https://homebrewery.naturalcrit.com', - 'http://localhost:8000', - 'http://localhost:8010', - 'https://naturalcrit.com' - ]; //allow natcrit local and live to call - if (!origin || allowedOrigins.includes(origin)) { + 'https://homebrewery.naturalcrit.com', + 'http://localhost:8000', + 'http://localhost:8010', + 'https://naturalcrit.com' + ]; + + const herokuRegex = /^https:\/\/.*\.herokuapp\.com$/; // Matches any Heroku app + + if (!origin || allowedOrigins.includes(origin) || herokuRegex.test(origin)) { callback(null, true); } else { - console.log(origin, 'not allowed'); + console.log(origin, 'not allowed'); callback(new Error('Not allowed by CORS, if you think this is an error, please contact us')); } }, @@ -78,6 +80,7 @@ const corsOptions = { credentials: true, }; + app.use(cors(corsOptions)); //Account Middleware From c29e1905bf4a578a42e1dd6fd86b89f3d0621c7a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=ADctor=20Losada=20Hern=C3=A1ndez?= Date: Tue, 10 Dec 2024 19:24:23 +0100 Subject: [PATCH 08/17] add localhost to allowed origins only if in local, also remake regex --- server/app.js | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/server/app.js b/server/app.js index de44f0609..4c6c9ba1f 100644 --- a/server/app.js +++ b/server/app.js @@ -57,17 +57,24 @@ app.use(forceSSL); import cors from 'cors'; -// CORS Configuration +const nodeEnv = config.get('node_env'); +const isLocalEnvironment = config.get('local_environments').includes(nodeEnv); + const corsOptions = { origin: (origin, callback) => { + const allowedOrigins = [ 'https://homebrewery.naturalcrit.com', - 'http://localhost:8000', - 'http://localhost:8010', - 'https://naturalcrit.com' + 'https://naturalcrit.com', + 'https://naturalcrit-stage.herokuapp.com', + 'https://homebrewery-stage.herokuapp.com', ]; - const herokuRegex = /^https:\/\/.*\.herokuapp\.com$/; // Matches any Heroku app + if (isLocalEnvironment) { + allowedOrigins.push('http://localhost:8000', 'http://localhost:8010'); + } + + const herokuRegex = /^https:\/\/(?:homebrewery-pr-\d+\.herokuapp\.com|naturalcrit-pr-\d+\.herokuapp\.com)$/; // Matches any Heroku app if (!origin || allowedOrigins.includes(origin) || herokuRegex.test(origin)) { callback(null, true); @@ -80,7 +87,6 @@ const corsOptions = { credentials: true, }; - app.use(cors(corsOptions)); //Account Middleware @@ -505,8 +511,6 @@ app.get('/account', asyncHandler(async (req, res, next)=>{ return next(); })); -const nodeEnv = config.get('node_env'); -const isLocalEnvironment = config.get('local_environments').includes(nodeEnv); // Local only if(isLocalEnvironment){ // Login From 5e5c637c79b252e4d5a1003bb0a9ce8235e4e76a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=ADctor=20Losada=20Hern=C3=A1ndez?= Date: Sat, 14 Dec 2024 20:59:51 +0100 Subject: [PATCH 09/17] revert api catch on wrong route middleware --- server/app.js | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/server/app.js b/server/app.js index 4c6c9ba1f..b10f36c4e 100644 --- a/server/app.js +++ b/server/app.js @@ -346,7 +346,7 @@ app.get('/user/:username', async (req, res, next)=>{ return next(); }); -//Rename Brews +//Change author name on brews app.put('/api/user/rename', async (req, res) => { const { username, newUsername } = req.body; @@ -538,14 +538,11 @@ app.get('/vault', asyncHandler(async(req, res, next)=>{ //Send rendered page app.use(asyncHandler(async (req, res, next) => { - if (!req.route && !req.path.startsWith('/api/')) { - return res.redirect('/'); - } + if (!req.route) return res.redirect('/'); // Catch-all for invalid routes - const page = await renderPage(req, res); - if (!page) return; - - res.send(page); + const page = await renderPage(req, res); + if(!page) return; + res.send(page); })); //Render the page From a1c228b1d1fb03b8b11e6ae1f1089d5c47b9434e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=ADctor=20Losada=20Hern=C3=A1ndez?= Date: Sat, 14 Dec 2024 21:01:38 +0100 Subject: [PATCH 10/17] log req account --- server/app.js | 2 ++ 1 file changed, 2 insertions(+) diff --git a/server/app.js b/server/app.js index b10f36c4e..6108c380d 100644 --- a/server/app.js +++ b/server/app.js @@ -277,6 +277,7 @@ app.get('/css/:id', asyncHandler(getBrew('share')), (req, res)=>{getCSS(req, res //User Page app.get('/user/:username', async (req, res, next)=>{ const ownAccount = req.account && (req.account.username == req.params.username); + console.log(req.account); req.ogMeta = { ...defaultMetaTags, title : `${req.params.username}'s Collection`, @@ -348,6 +349,7 @@ app.get('/user/:username', async (req, res, next)=>{ //Change author name on brews app.put('/api/user/rename', async (req, res) => { + console.log(req.account); const { username, newUsername } = req.body; console.log('renaming'); From f0c094e9d80459eb9ac9db2e9fb74eff7a1f1740 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=ADctor=20Losada=20Hern=C3=A1ndez?= Date: Sat, 14 Dec 2024 21:12:35 +0100 Subject: [PATCH 11/17] logs to account middleware --- server/app.js | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/server/app.js b/server/app.js index 6108c380d..40ec19ab6 100644 --- a/server/app.js +++ b/server/app.js @@ -91,12 +91,16 @@ app.use(cors(corsOptions)); //Account Middleware app.use((req, res, next)=>{ + console.log('passing through acc middleware') if(req.cookies && req.cookies.nc_session){ try { + console.log(`creating req.account equal to "${jwt.decode(req.cookies.nc_session, config.get('secret'))}"`); req.account = jwt.decode(req.cookies.nc_session, config.get('secret')); //console.log("Just loaded up JWT from cookie:"); //console.log(req.account); - } catch (e){} + } catch (e){ + console.log(e); + } } req.config = { From 666a94cd658c0ca71a3546db4f30bf0a1b724b98 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=ADctor=20Losada=20Hern=C3=A1ndez?= Date: Sat, 14 Dec 2024 21:15:16 +0100 Subject: [PATCH 12/17] fix log --- server/app.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server/app.js b/server/app.js index 40ec19ab6..0b0cfb9d2 100644 --- a/server/app.js +++ b/server/app.js @@ -94,7 +94,7 @@ app.use((req, res, next)=>{ console.log('passing through acc middleware') if(req.cookies && req.cookies.nc_session){ try { - console.log(`creating req.account equal to "${jwt.decode(req.cookies.nc_session, config.get('secret'))}"`); + console.log(`creating req.account equal to "${JSON.stringify(jwt.decode(req.cookies.nc_session, config.get('secret')))}"`); req.account = jwt.decode(req.cookies.nc_session, config.get('secret')); //console.log("Just loaded up JWT from cookie:"); //console.log(req.account); From 4f57f006ce86154fe170e28b9950029295315e1b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=ADctor=20Losada=20Hern=C3=A1ndez?= Date: Sat, 14 Dec 2024 21:20:39 +0100 Subject: [PATCH 13/17] log cookies at auth middleware --- server/app.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server/app.js b/server/app.js index 0b0cfb9d2..73eb876f8 100644 --- a/server/app.js +++ b/server/app.js @@ -91,7 +91,7 @@ app.use(cors(corsOptions)); //Account Middleware app.use((req, res, next)=>{ - console.log('passing through acc middleware') + console.log('passing through acc middleware, checking for cookies now: does cookies exist? ', !!req.cookies, ', ok, does the session cookie exist? ', !!req.cookies.nc_session); if(req.cookies && req.cookies.nc_session){ try { console.log(`creating req.account equal to "${JSON.stringify(jwt.decode(req.cookies.nc_session, config.get('secret')))}"`); From b26526a2f10626eadb897f530823de73f4853589 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=ADctor=20Losada=20Hern=C3=A1ndez?= Date: Sat, 14 Dec 2024 22:24:52 +0100 Subject: [PATCH 14/17] lint and logging pass prepared for in server auth from this end --- server/app.js | 102 +++++++++++++++++++++++++------------------------- 1 file changed, 50 insertions(+), 52 deletions(-) diff --git a/server/app.js b/server/app.js index 73eb876f8..58132b6f0 100644 --- a/server/app.js +++ b/server/app.js @@ -2,7 +2,7 @@ // Set working directory to project root import { dirname } from 'path'; import { fileURLToPath } from 'url'; -import packageJSON from './../package.json' with { type: "json" }; +import packageJSON from './../package.json' with { type: 'json' }; const __dirname = dirname(fileURLToPath(import.meta.url)); process.chdir(`${__dirname}/..`); @@ -26,7 +26,7 @@ import serveCompressedStaticAssets from './static-assets.mv.js'; import sanitizeFilename from 'sanitize-filename'; import asyncHandler from 'express-async-handler'; import templateFn from '../client/template.js'; -import {model as HomebrewModel } from './homebrew.model.js'; +import { model as HomebrewModel } from './homebrew.model.js'; import { DEFAULT_BREW } from './brewDefaults.js'; import { splitTextStyleAndMetadata } from '../shared/helpers.js'; @@ -47,7 +47,7 @@ const sanitizeBrew = (brew, accessType)=>{ return brew; }; -app.set('trust proxy', 1 /* number of proxies between user and server */) +app.set('trust proxy', 1 /* number of proxies between user and server */); app.use('/', serveCompressedStaticAssets(`build`)); app.use(contentNegotiation); @@ -61,30 +61,30 @@ const nodeEnv = config.get('node_env'); const isLocalEnvironment = config.get('local_environments').includes(nodeEnv); const corsOptions = { - origin: (origin, callback) => { + origin : (origin, callback)=>{ - const allowedOrigins = [ - 'https://homebrewery.naturalcrit.com', - 'https://naturalcrit.com', - 'https://naturalcrit-stage.herokuapp.com', - 'https://homebrewery-stage.herokuapp.com', - ]; + const allowedOrigins = [ + 'https://homebrewery.naturalcrit.com', + 'https://naturalcrit.com', + 'https://naturalcrit-stage.herokuapp.com', + 'https://homebrewery-stage.herokuapp.com', + ]; - if (isLocalEnvironment) { - allowedOrigins.push('http://localhost:8000', 'http://localhost:8010'); - } + if(isLocalEnvironment) { + allowedOrigins.push('http://localhost:8000', 'http://localhost:8010'); + } - const herokuRegex = /^https:\/\/(?:homebrewery-pr-\d+\.herokuapp\.com|naturalcrit-pr-\d+\.herokuapp\.com)$/; // Matches any Heroku app + const herokuRegex = /^https:\/\/(?:homebrewery-pr-\d+\.herokuapp\.com|naturalcrit-pr-\d+\.herokuapp\.com)$/; // Matches any Heroku app - if (!origin || allowedOrigins.includes(origin) || herokuRegex.test(origin)) { - callback(null, true); - } else { - console.log(origin, 'not allowed'); - callback(new Error('Not allowed by CORS, if you think this is an error, please contact us')); - } - }, - methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'], - credentials: true, + if(!origin || allowedOrigins.includes(origin) || herokuRegex.test(origin)) { + callback(null, true); + } else { + console.log(origin, 'not allowed'); + callback(new Error('Not allowed by CORS, if you think this is an error, please contact us')); + } + }, + methods : ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'], + credentials : true, }; app.use(cors(corsOptions)); @@ -94,7 +94,6 @@ app.use((req, res, next)=>{ console.log('passing through acc middleware, checking for cookies now: does cookies exist? ', !!req.cookies, ', ok, does the session cookie exist? ', !!req.cookies.nc_session); if(req.cookies && req.cookies.nc_session){ try { - console.log(`creating req.account equal to "${JSON.stringify(jwt.decode(req.cookies.nc_session, config.get('secret')))}"`); req.account = jwt.decode(req.cookies.nc_session, config.get('secret')); //console.log("Just loaded up JWT from cookie:"); //console.log(req.account); @@ -312,7 +311,7 @@ app.get('/user/:username', async (req, res, next)=>{ console.log(err); }); - brews.forEach(brew => brew.stubbed = true); //All brews from MongoDB are "stubbed" + brews.forEach((brew)=>brew.stubbed = true); //All brews from MongoDB are "stubbed" if(ownAccount && req?.account?.googleId){ const auth = await GoogleActions.authCheck(req.account, res); @@ -352,33 +351,32 @@ app.get('/user/:username', async (req, res, next)=>{ }); //Change author name on brews -app.put('/api/user/rename', async (req, res) => { +app.put('/api/user/rename', async (req, res)=>{ console.log(req.account); - const { username, newUsername } = req.body; - + const { username, newUsername } = req.body; + console.log(`is user ${req.account.username} equal to ${username}? ${req.account.username === username} ${req.account.username === username && 'then add the damn auth for renaming!'}`); console.log('renaming'); - if (!username || !newUsername) { - return res.status(400).json({ error: 'Username and newUsername are required.' }); - } - try { - const brews = await HomebrewModel.getByUser(username, true, ['authors']); - const renamePromises = brews.map(async (brew) => { - const updatedAuthors = brew.authors.map((author) => - author === username ? newUsername : author - ); - return HomebrewModel.updateOne( - { _id: brew._id }, - { $set: { authors: updatedAuthors } } - ); - }); - await Promise.all(renamePromises); + if(!username || !newUsername) { + return res.status(400).json({ error: 'Username and newUsername are required.' }); + } + try { + const brews = await HomebrewModel.getByUser(username, true, ['authors']); + const renamePromises = brews.map(async (brew)=>{ + const updatedAuthors = brew.authors.map((author)=>author === username ? newUsername : author + ); + return HomebrewModel.updateOne( + { _id: brew._id }, + { $set: { authors: updatedAuthors } } + ); + }); + await Promise.all(renamePromises); - return res.json({ success: true, message: `Brews for ${username} renamed to ${newUsername}.` }); - } catch (error) { - console.error('Error renaming brews:', error); - return res.status(500).json({ error: 'Failed to rename brews.' }); - } + return res.json({ success: true, message: `Brews for ${username} renamed to ${newUsername}.` }); + } catch (error) { + console.error('Error renaming brews:', error); + return res.status(500).json({ error: 'Failed to rename brews.' }); + } }); //Edit Page @@ -468,7 +466,7 @@ app.get('/share/:id', asyncHandler(getBrew('share')), asyncHandler(async (req, r app.get('/account', asyncHandler(async (req, res, next)=>{ const data = {}; data.title = 'Account Information Page'; - + if(!req.account) { res.set('WWW-Authenticate', 'Bearer realm="Authorization Required"'); const error = new Error('No valid account'); @@ -482,7 +480,7 @@ app.get('/account', asyncHandler(async (req, res, next)=>{ let googleCount = []; if(req.account) { if(req.account.googleId) { - auth = await GoogleActions.authCheck(req.account, res, false) + auth = await GoogleActions.authCheck(req.account, res, false); googleCount = await GoogleActions.listGoogleBrews(auth) .catch((err)=>{ @@ -543,8 +541,8 @@ app.get('/vault', asyncHandler(async(req, res, next)=>{ })); //Send rendered page -app.use(asyncHandler(async (req, res, next) => { - if (!req.route) return res.redirect('/'); // Catch-all for invalid routes +app.use(asyncHandler(async (req, res, next)=>{ + if(!req.route) return res.redirect('/'); // Catch-all for invalid routes const page = await renderPage(req, res); if(!page) return; From afc92c4545fd1529daedd7fca5e0dacec29590c6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=ADctor=20Losada=20Hern=C3=A1ndez?= Date: Sat, 14 Dec 2024 22:30:24 +0100 Subject: [PATCH 15/17] fix check client version middleware to stop checking outside calls --- server/middleware/check-client-version.js | 26 ++++++++++++++--------- 1 file changed, 16 insertions(+), 10 deletions(-) diff --git a/server/middleware/check-client-version.js b/server/middleware/check-client-version.js index 19cb40b25..dcb18dace 100644 --- a/server/middleware/check-client-version.js +++ b/server/middleware/check-client-version.js @@ -1,16 +1,22 @@ import packageJSON from '../../package.json' with { type: "json" }; -const version = packageJSON.version; -//This should be only for internal calls, but right now prevents spam api calls, this should be done with a proper cors policy +export default (req, res, next) => { + const origin = req.get('Origin'); + const sameSite = req.get('Host'); -export default (req, res, next)=>{ - const userVersion = req.get('Homebrewery-Version'); + if (origin && origin !== `http://${sameSite}` && origin !== `https://${sameSite}`) { + return next(); // Skip version check if the request is from another site, like naturalcrit.com + } - if(userVersion != version) { - return res.status(412).send({ - message : `Client version ${userVersion} is out of date. Please save your changes elsewhere and refresh to pick up client version ${version}.` - }); - } + const userVersion = req.get('Homebrewery-Version'); + const version = packageJSON.version; - next(); + if (userVersion !== version) { + return res.status(412).send({ + message: `Client version ${userVersion} is out of date. Please save your changes elsewhere and refresh to pick up client version ${version}.` + }); + } + + next(); }; + From 99f2972079561b6f996756b36c2af842e06e7005 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=ADctor=20Losada=20Hern=C3=A1ndez?= Date: Sat, 14 Dec 2024 23:34:12 +0100 Subject: [PATCH 16/17] fixes as asked --- server/app.js | 2 -- server/homebrew.api.js | 11 +++++---- server/middleware/check-client-version.js | 27 +++++++++-------------- 3 files changed, 15 insertions(+), 25 deletions(-) diff --git a/server/app.js b/server/app.js index 58132b6f0..0d82642d9 100644 --- a/server/app.js +++ b/server/app.js @@ -280,7 +280,6 @@ app.get('/css/:id', asyncHandler(getBrew('share')), (req, res)=>{getCSS(req, res //User Page app.get('/user/:username', async (req, res, next)=>{ const ownAccount = req.account && (req.account.username == req.params.username); - console.log(req.account); req.ogMeta = { ...defaultMetaTags, title : `${req.params.username}'s Collection`, @@ -352,7 +351,6 @@ app.get('/user/:username', async (req, res, next)=>{ //Change author name on brews app.put('/api/user/rename', async (req, res)=>{ - console.log(req.account); const { username, newUsername } = req.body; console.log(`is user ${req.account.username} equal to ${username}? ${req.account.username === username} ${req.account.username === username && 'then add the damn auth for renaming!'}`); console.log('renaming'); diff --git a/server/homebrew.api.js b/server/homebrew.api.js index a75887742..159c08b47 100644 --- a/server/homebrew.api.js +++ b/server/homebrew.api.js @@ -467,12 +467,11 @@ const api = { } }; -router.use('/api', checkClientVersion); -router.post('/api', asyncHandler(api.newBrew)); -router.put('/api/:id', asyncHandler(api.getBrew('edit', true)), asyncHandler(api.updateBrew)); -router.put('/api/update/:id', asyncHandler(api.getBrew('edit', true)), asyncHandler(api.updateBrew)); -router.delete('/api/:id', asyncHandler(api.deleteBrew)); -router.get('/api/remove/:id', asyncHandler(api.deleteBrew)); +router.post('/api', checkClientVersion, asyncHandler(api.newBrew)); +router.put('/api/:id', checkClientVersion, asyncHandler(api.getBrew('edit', true)), asyncHandler(api.updateBrew)); +router.put('/api/update/:id', checkClientVersion, asyncHandler(api.getBrew('edit', true)), asyncHandler(api.updateBrew)); +router.delete('/api/:id', checkClientVersion, asyncHandler(api.deleteBrew)); +router.get('/api/remove/:id', checkClientVersion, asyncHandler(api.deleteBrew)); router.get('/api/theme/:renderer/:id', asyncHandler(api.getThemeBundle)); export default api; \ No newline at end of file diff --git a/server/middleware/check-client-version.js b/server/middleware/check-client-version.js index dcb18dace..45d868a5a 100644 --- a/server/middleware/check-client-version.js +++ b/server/middleware/check-client-version.js @@ -1,22 +1,15 @@ -import packageJSON from '../../package.json' with { type: "json" }; +import packageJSON from '../../package.json' with { type: 'json' }; -export default (req, res, next) => { - const origin = req.get('Origin'); - const sameSite = req.get('Host'); +export default (req, res, next)=>{ + const userVersion = req.get('Homebrewery-Version'); + const version = packageJSON.version; - if (origin && origin !== `http://${sameSite}` && origin !== `https://${sameSite}`) { - return next(); // Skip version check if the request is from another site, like naturalcrit.com - } + if(userVersion !== version) { + return res.status(412).send({ + message : `Client version ${userVersion} is out of date. Please save your changes elsewhere and refresh to pick up client version ${version}.` + }); + } - const userVersion = req.get('Homebrewery-Version'); - const version = packageJSON.version; - - if (userVersion !== version) { - return res.status(412).send({ - message: `Client version ${userVersion} is out of date. Please save your changes elsewhere and refresh to pick up client version ${version}.` - }); - } - - next(); + next(); }; From a9275698faecbc8211311591380dacb872dd4617 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=ADctor=20Losada=20Hern=C3=A1ndez?= Date: Sat, 14 Dec 2024 23:41:05 +0100 Subject: [PATCH 17/17] add comment to tell future me to remove logs when feature comes --- server/app.js | 3 +++ 1 file changed, 3 insertions(+) diff --git a/server/app.js b/server/app.js index 0d82642d9..39086cc21 100644 --- a/server/app.js +++ b/server/app.js @@ -352,6 +352,9 @@ app.get('/user/:username', async (req, res, next)=>{ //Change author name on brews app.put('/api/user/rename', async (req, res)=>{ const { username, newUsername } = req.body; + + //this next logs will be removed in a next PR, as i need to get this live to test if req.account is created when passing the request from naturalcrit.com + console.log(`is user ${req.account.username} equal to ${username}? ${req.account.username === username} ${req.account.username === username && 'then add the damn auth for renaming!'}`); console.log('renaming');