0
0
mirror of https://github.com/naturalcrit/homebrewery.git synced 2026-01-11 17:42:42 +00:00

lint and logging pass prepared for in server auth from this end

This commit is contained in:
Víctor Losada Hernández
2024-12-14 22:24:52 +01:00
parent 4f57f006ce
commit b26526a2f1

View File

@@ -2,7 +2,7 @@
// Set working directory to project root // Set working directory to project root
import { dirname } from 'path'; import { dirname } from 'path';
import { fileURLToPath } from 'url'; 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)); const __dirname = dirname(fileURLToPath(import.meta.url));
process.chdir(`${__dirname}/..`); process.chdir(`${__dirname}/..`);
@@ -26,7 +26,7 @@ import serveCompressedStaticAssets from './static-assets.mv.js';
import sanitizeFilename from 'sanitize-filename'; import sanitizeFilename from 'sanitize-filename';
import asyncHandler from 'express-async-handler'; import asyncHandler from 'express-async-handler';
import templateFn from '../client/template.js'; 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 { DEFAULT_BREW } from './brewDefaults.js';
import { splitTextStyleAndMetadata } from '../shared/helpers.js'; import { splitTextStyleAndMetadata } from '../shared/helpers.js';
@@ -47,7 +47,7 @@ const sanitizeBrew = (brew, accessType)=>{
return brew; 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('/', serveCompressedStaticAssets(`build`));
app.use(contentNegotiation); app.use(contentNegotiation);
@@ -61,30 +61,30 @@ const nodeEnv = config.get('node_env');
const isLocalEnvironment = config.get('local_environments').includes(nodeEnv); const isLocalEnvironment = config.get('local_environments').includes(nodeEnv);
const corsOptions = { const corsOptions = {
origin: (origin, callback) => { origin : (origin, callback)=>{
const allowedOrigins = [ const allowedOrigins = [
'https://homebrewery.naturalcrit.com', 'https://homebrewery.naturalcrit.com',
'https://naturalcrit.com', 'https://naturalcrit.com',
'https://naturalcrit-stage.herokuapp.com', 'https://naturalcrit-stage.herokuapp.com',
'https://homebrewery-stage.herokuapp.com', 'https://homebrewery-stage.herokuapp.com',
]; ];
if (isLocalEnvironment) { if(isLocalEnvironment) {
allowedOrigins.push('http://localhost:8000', 'http://localhost:8010'); 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)) { if(!origin || allowedOrigins.includes(origin) || herokuRegex.test(origin)) {
callback(null, true); callback(null, true);
} else { } 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')); callback(new Error('Not allowed by CORS, if you think this is an error, please contact us'));
} }
}, },
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'], methods : ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
credentials: true, credentials : true,
}; };
app.use(cors(corsOptions)); 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); 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){ if(req.cookies && req.cookies.nc_session){
try { 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')); req.account = jwt.decode(req.cookies.nc_session, config.get('secret'));
//console.log("Just loaded up JWT from cookie:"); //console.log("Just loaded up JWT from cookie:");
//console.log(req.account); //console.log(req.account);
@@ -312,7 +311,7 @@ app.get('/user/:username', async (req, res, next)=>{
console.log(err); 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){ if(ownAccount && req?.account?.googleId){
const auth = await GoogleActions.authCheck(req.account, res); 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 //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); 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'); console.log('renaming');
if (!username || !newUsername) { if(!username || !newUsername) {
return res.status(400).json({ error: 'Username and newUsername are required.' }); return res.status(400).json({ error: 'Username and newUsername are required.' });
} }
try { try {
const brews = await HomebrewModel.getByUser(username, true, ['authors']); const brews = await HomebrewModel.getByUser(username, true, ['authors']);
const renamePromises = brews.map(async (brew) => { const renamePromises = brews.map(async (brew)=>{
const updatedAuthors = brew.authors.map((author) => const updatedAuthors = brew.authors.map((author)=>author === username ? newUsername : author
author === username ? newUsername : author );
); return HomebrewModel.updateOne(
return HomebrewModel.updateOne( { _id: brew._id },
{ _id: brew._id }, { $set: { authors: updatedAuthors } }
{ $set: { authors: updatedAuthors } } );
); });
}); await Promise.all(renamePromises);
await Promise.all(renamePromises);
return res.json({ success: true, message: `Brews for ${username} renamed to ${newUsername}.` }); return res.json({ success: true, message: `Brews for ${username} renamed to ${newUsername}.` });
} catch (error) { } catch (error) {
console.error('Error renaming brews:', error); console.error('Error renaming brews:', error);
return res.status(500).json({ error: 'Failed to rename brews.' }); return res.status(500).json({ error: 'Failed to rename brews.' });
} }
}); });
//Edit Page //Edit Page
@@ -482,7 +480,7 @@ app.get('/account', asyncHandler(async (req, res, next)=>{
let googleCount = []; let googleCount = [];
if(req.account) { if(req.account) {
if(req.account.googleId) { 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) googleCount = await GoogleActions.listGoogleBrews(auth)
.catch((err)=>{ .catch((err)=>{
@@ -543,8 +541,8 @@ app.get('/vault', asyncHandler(async(req, res, next)=>{
})); }));
//Send rendered page //Send rendered page
app.use(asyncHandler(async (req, res, next) => { app.use(asyncHandler(async (req, res, next)=>{
if (!req.route) return res.redirect('/'); // Catch-all for invalid routes if(!req.route) return res.redirect('/'); // Catch-all for invalid routes
const page = await renderPage(req, res); const page = await renderPage(req, res);
if(!page) return; if(!page) return;