diff --git a/functions/db-controllers/food-controllers.js b/functions/db-controllers/food-controllers.js index 0d7c2f2..d19a426 100644 --- a/functions/db-controllers/food-controllers.js +++ b/functions/db-controllers/food-controllers.js @@ -5,143 +5,143 @@ const Food = require('../models/food'); const User = require('../models/user'); const getFoods = async (req, res, next) => { -const userId = req.userData.userId; - -let userWithFood; -try { - userWithFood = await User.findById(userId).populate('foods'); -} catch (err) { - console.error(err); - const error = new HttpError( - 'Could not find food. Try again later.', 500 - ); - return next(error); -} - -if (!userWithFood) { - console.error('Could not find user by id'); - return next( - new HttpError('Could not find food. Try again later.', 404) - ); -} - -res.json({ - foods: userWithFood.foods.map(food => - food.toObject({ getters: true }) - ) -}); + const userId = req.userData.userId; + + let userWithFood; + try { + userWithFood = await User.findById(userId).populate('foods'); + } catch (err) { + console.error(err); + const error = new HttpError( + 'Could not find food. Try again later.', 500 + ); + return next(error); + } + + if (!userWithFood) { + console.error('Could not find user by id'); + return next( + new HttpError('Could not find food. Try again later.', 404) + ); + } + + res.json({ + foods: userWithFood.foods.map(food => + food.toObject({ getters: true }) + ) + }); }; const createFood = async (req, res, next) => { -const { food } = req.body; - -const createdFood = new Food({ - food, - creator: req.userData.userId -}); - -let user; -try { - user = await User.findById(req.userData.userId); -} catch (err) { - console.error(err); - const error = new HttpError('Could not add food to favorites. Try again later.', 500); - return next(error); -} - -if (!user) { - console.error('Could not find user by id'); - const error = new HttpError('Could not add food to favorites. Try again later.', 404); - return next(error); -} - -let existingFood -try { - existingFood = await Food.findOne({ "food.food.label": food.food.label, "creator": req.userData.userId}) -} catch (err) { - console.error(err); - const error = new HttpError( - 'Could not add food to favorites. Try again later.', - 500 - ); - return next(error); -} - -if (existingFood) { - const error = new HttpError( - 'Food exists already.', - 422 - ); - return next(error); -} - -try { - const sess = await mongoose.startSession(); - sess.startTransaction(); - await createdFood.save({ session: sess }); - user.foods.push(createdFood); - await user.save({ session: sess }); - await sess.commitTransaction(); -} catch (err) { - console.error(err); - const error = new HttpError( - 'Could not add food to favorites. Try again later.', - 500 - ); - return next(error); -} - -res.status(201).json({ food: createdFood }); + const { food } = req.body; + + const createdFood = new Food({ + food, + creator: req.userData.userId + }); + + let user; + try { + user = await User.findById(req.userData.userId); + } catch (err) { + console.error(err); + const error = new HttpError('Could not add food to favorites. Try again later.', 500); + return next(error); + } + + if (!user) { + console.error('Could not find user by id'); + const error = new HttpError('Could not add food to favorites. Try again later.', 404); + return next(error); + } + + let existingFood + try { + existingFood = await Food.findOne({ "food.food.label": food.food.label, "creator": req.userData.userId}) + } catch (err) { + console.error(err); + const error = new HttpError( + 'Could not add food to favorites. Try again later.', + 500 + ); + return next(error); + } + + if (existingFood) { + const error = new HttpError( + 'Food exists already.', + 422 + ); + return next(error); + } + + try { + const sess = await mongoose.startSession(); + sess.startTransaction(); + await createdFood.save({ session: sess }); + user.foods.push(createdFood); + await user.save({ session: sess }); + await sess.commitTransaction(); + } catch (err) { + console.error(err); + const error = new HttpError( + 'Could not add food to favorites. Try again later.', + 500 + ); + return next(error); + } + + res.status(201).json({ food: createdFood }); }; const deleteFood = async (req, res, next) => { -const foodId = req.params.pid; - -let food; -try { - food = await Food.findById(foodId).populate('creator'); -} catch (err) { - console.error(err); - const error = new HttpError( - 'Could not delete food. Try again later.', - 500 - ); - return next(error); -} - -if (!food) { - console.error('Could not find food by id'); - const error = new HttpError('Could not delete food. Try again later.', 404); - return next(error); -} - -if (food.creator.id !== req.userData.userId) { - console.error('Not authorized') - const error = new HttpError( - 'You are not allowed to delete this food.', - 401 - ); - return next(error); -} - -try { - const sess = await mongoose.startSession(); - sess.startTransaction(); - await food.deleteOne({ session: sess }); - food.creator.foods.pull(food); - await food.creator.save({ session: sess }); - await sess.commitTransaction(); -} catch (err) { - console.error(err); - const error = new HttpError( - 'Could not delete food. Try again later.', - 500 - ); - return next(error); -} - -res.status(200).json({ message: 'Deleted food.' }); + const foodId = req.params.pid; + + let food; + try { + food = await Food.findById(foodId).populate('creator'); + } catch (err) { + console.error(err); + const error = new HttpError( + 'Could not delete food. Try again later.', + 500 + ); + return next(error); + } + + if (!food) { + console.error('Could not find food by id'); + const error = new HttpError('Could not delete food. Try again later.', 404); + return next(error); + } + + if (food.creator.id !== req.userData.userId) { + console.error('Not authorized') + const error = new HttpError( + 'You are not allowed to delete this food.', + 401 + ); + return next(error); + } + + try { + const sess = await mongoose.startSession(); + sess.startTransaction(); + await food.deleteOne({ session: sess }); + food.creator.foods.pull(food); + await food.creator.save({ session: sess }); + await sess.commitTransaction(); + } catch (err) { + console.error(err); + const error = new HttpError( + 'Could not delete food. Try again later.', + 500 + ); + return next(error); + } + + res.status(200).json({ message: 'Deleted food.' }); }; exports.getFoods = getFoods; diff --git a/functions/db-controllers/menu-controllers.js b/functions/db-controllers/menu-controllers.js index 16b2fe0..540a3db 100644 --- a/functions/db-controllers/menu-controllers.js +++ b/functions/db-controllers/menu-controllers.js @@ -5,193 +5,193 @@ const Menu = require('../models/menu'); const User = require('../models/user'); const getMenus = async (req, res, next) => { -const userId = req.userData.userId; - -let userWithMenu; -try { - userWithMenu = await User.findById(userId).populate('menus'); -} catch (err) { - console.error(err); - const error = new HttpError( - 'Could not find menu. Try again later.', - 500 - ); - return next(error); -} - -if (!userWithMenu) { - console.error('Could not find menu by id.') - return next( - new HttpError('Could not find menu. Try again later.', 404) - ); -} - -res.json({ - menus: userWithMenu.menus.map(menu => - menu.toObject({ getters: true }) - ) -}); + const userId = req.userData.userId; + + let userWithMenu; + try { + userWithMenu = await User.findById(userId).populate('menus'); + } catch (err) { + console.error(err); + const error = new HttpError( + 'Could not find menu. Try again later.', + 500 + ); + return next(error); + } + + if (!userWithMenu) { + console.error('Could not find menu by id.') + return next( + new HttpError('Could not find menu. Try again later.', 404) + ); + } + + res.json({ + menus: userWithMenu.menus.map(menu => + menu.toObject({ getters: true }) + ) + }); }; const createMenu = async (req, res, next) => { -const { menu } = req.body; - -console.log(menu); - -const createdMenu = new Menu({ - menu, - creator: req.userData.userId -}); - -let user; -try { - user = await User.findById(req.userData.userId); -} catch (err) { - console.error(err); - const error = new HttpError('Could not add menu to favorites. Try again later.', 500); - return next(error); -} - -if (!user) { - console.error('Could not find user by id.'); - const error = new HttpError('Could not add menu to favorites. Try again later.', 404); - return next(error); -} - -let existingMenu -try { - existingMenu = await Menu.findOne({ "menu.name": menu.name, "creator": req.userData.userId}) -} catch (err) { - console.error(err); - const error = new HttpError( - 'Could not add menu to favorites. Try again later.', - 500 - ); - return next(error); -} - -if (existingMenu) { - const error = new HttpError( - 'Menu with this name exists already.', - 422 - ); - return next(error); -} - -try { - const sess = await mongoose.startSession(); - sess.startTransaction(); - await createdMenu.save({ session: sess }); - user.menus.push(createdMenu); - await user.save({ session: sess }); - await sess.commitTransaction(); -} catch (err) { - console.error(err); - const error = new HttpError( - 'Could not add menu to favorites. Try again later.', - 500 - ); - return next(error); -} - -res.status(201).json({ menu: createdMenu }); + const { menu } = req.body; + + console.log(menu); + + const createdMenu = new Menu({ + menu, + creator: req.userData.userId + }); + + let user; + try { + user = await User.findById(req.userData.userId); + } catch (err) { + console.error(err); + const error = new HttpError('Could not add menu to favorites. Try again later.', 500); + return next(error); + } + + if (!user) { + console.error('Could not find user by id.'); + const error = new HttpError('Could not add menu to favorites. Try again later.', 404); + return next(error); + } + + let existingMenu + try { + existingMenu = await Menu.findOne({ "menu.name": menu.name, "creator": req.userData.userId}) + } catch (err) { + console.error(err); + const error = new HttpError( + 'Could not add menu to favorites. Try again later.', + 500 + ); + return next(error); + } + + if (existingMenu) { + const error = new HttpError( + 'Menu with this name exists already.', + 422 + ); + return next(error); + } + + try { + const sess = await mongoose.startSession(); + sess.startTransaction(); + await createdMenu.save({ session: sess }); + user.menus.push(createdMenu); + await user.save({ session: sess }); + await sess.commitTransaction(); + } catch (err) { + console.error(err); + const error = new HttpError( + 'Could not add menu to favorites. Try again later.', + 500 + ); + return next(error); + } + + res.status(201).json({ menu: createdMenu }); }; const updateMenu = async (req, res, next) => { -const { updatedMenu } = req.body; -const menuId = req.params.pid; -console.log(updatedMenu); - -let menu; -try { - menu = await Menu.findById(menuId); -} catch (err) { - console.error(err); - const error = new HttpError( - 'Could not update menu in favorites. Try again later.', - 500 - ); - return next(error); -} - -if (!menu) { - console.error('Could not find menu by id.'); - const error = new HttpError('Could not update menu in favorites. Try again later.', 404); - return next(error); -} - -if (menu.creator.toString() !== req.userData.userId) { - console.error('Not authorized.'); - const error = new HttpError('You are not allowed to edit this menu.', 401); - return next(error); -} - - -menu.menu = updatedMenu; - -try { - await menu.save(); -} catch (err) { - console.error(err); - const error = new HttpError( + const { updatedMenu } = req.body; + const menuId = req.params.pid; + console.log(updatedMenu); + + let menu; + try { + menu = await Menu.findById(menuId); + } catch (err) { + console.error(err); + const error = new HttpError( 'Could not update menu in favorites. Try again later.', 500 - ); - return next(error); -} - -res.status(200).json({ menu: menu.toObject({ getters: true }) }); + ); + return next(error); + } + + if (!menu) { + console.error('Could not find menu by id.'); + const error = new HttpError('Could not update menu in favorites. Try again later.', 404); + return next(error); + } + + if (menu.creator.toString() !== req.userData.userId) { + console.error('Not authorized.'); + const error = new HttpError('You are not allowed to edit this menu.', 401); + return next(error); + } + + + menu.menu = updatedMenu; + + try { + await menu.save(); + } catch (err) { + console.error(err); + const error = new HttpError( + 'Could not update menu in favorites. Try again later.', + 500 + ); + return next(error); + } + + res.status(200).json({ menu: menu.toObject({ getters: true }) }); }; const deleteMenu = async (req, res, next) => { -const menuId = req.params.pid; - -let menu; -try { - menu = await Menu.findById(menuId).populate('creator'); -} catch (err) { - console.error(err); - const error = new HttpError( - 'Could not delete menu. Try again later.', - 500 - ); - return next(error); -} - -if (!menu) { - console.error('Could not find menu by id.'); - const error = new HttpError('Could not delete menu. Try again later.', 404); - return next(error); -} - -if (menu.creator.id !== req.userData.userId) { - console.error('Not authorized'); - const error = new HttpError( - 'You are not allowed to delete this menu.', - 401 - ); - return next(error); -} - -try { - const sess = await mongoose.startSession(); - sess.startTransaction(); - await menu.deleteOne({ session: sess }); - menu.creator.menus.pull(menu); - await menu.creator.save({ session: sess }); - await sess.commitTransaction(); -} catch (err) { - console.error(err); - const error = new HttpError( - 'Could not delete menu. Try again later.', - 500 - ); - return next(error); -} - -res.status(200).json({ message: 'Deleted menu.' }); + const menuId = req.params.pid; + + let menu; + try { + menu = await Menu.findById(menuId).populate('creator'); + } catch (err) { + console.error(err); + const error = new HttpError( + 'Could not delete menu. Try again later.', + 500 + ); + return next(error); + } + + if (!menu) { + console.error('Could not find menu by id.'); + const error = new HttpError('Could not delete menu. Try again later.', 404); + return next(error); + } + + if (menu.creator.id !== req.userData.userId) { + console.error('Not authorized'); + const error = new HttpError( + 'You are not allowed to delete this menu.', + 401 + ); + return next(error); + } + + try { + const sess = await mongoose.startSession(); + sess.startTransaction(); + await menu.deleteOne({ session: sess }); + menu.creator.menus.pull(menu); + await menu.creator.save({ session: sess }); + await sess.commitTransaction(); + } catch (err) { + console.error(err); + const error = new HttpError( + 'Could not delete menu. Try again later.', + 500 + ); + return next(error); + } + + res.status(200).json({ message: 'Deleted menu.' }); }; exports.getMenus = getMenus; diff --git a/functions/db-controllers/recipe-controllers.js b/functions/db-controllers/recipe-controllers.js index 9137334..a5002c3 100644 --- a/functions/db-controllers/recipe-controllers.js +++ b/functions/db-controllers/recipe-controllers.js @@ -7,205 +7,205 @@ const Recipe = require('../models/recipe'); const User = require('../models/user'); const getRecipes = async (req, res, next) => { -const userId = req.userData.userId; - -let userWithRecipe; -try { - userWithRecipe = await User.findById(userId).populate('recipes'); -} catch (err) { - console.error(err); - const error = new HttpError( - 'Could not find recipe. Try again later.', - 500 - ); - return next(error); -} - -if (!userWithRecipe) { - console.error('Could not find user by id.'); - return next( - new HttpError('Could not find recipe. Try again later.', 404) - ); -} - -res.json({ - recipe: userWithRecipe.recipes.map(recipe => - recipe.toObject({ getters: true }) - ) -}); + const userId = req.userData.userId; + + let userWithRecipe; + try { + userWithRecipe = await User.findById(userId).populate('recipes'); + } catch (err) { + console.error(err); + const error = new HttpError( + 'Could not find recipe. Try again later.', + 500 + ); + return next(error); + } + + if (!userWithRecipe) { + console.error('Could not find user by id.'); + return next( + new HttpError('Could not find recipe. Try again later.', 404) + ); + } + + res.json({ + recipe: userWithRecipe.recipes.map(recipe => + recipe.toObject({ getters: true }) + ) + }); }; const createRecipe = async (req, res, next) => { -const { recipe } = req.body; -const parsedRecipe = JSON.parse(recipe); - -const createdRecipe = new Recipe({ - recipe: parsedRecipe, - image: req.image ? req.image.url : null, - creator: req.userData.userId -}); - -let user; -try { - user = await User.findById(req.userData.userId); -} catch (err) { - console.error(err); - const error = new HttpError('Could not add recipe to favorites. Try again later.', 500); - return next(error); -} - -if (!user) { - console.error('Could not find user by id.'); - const error = new HttpError('Could not add recipe to favorites. Try again later.', 404); - return next(error); -} - -let existingRecipe -try { - existingRecipe = await Recipe.findOne({ "recipe.name": parsedRecipe.name, "creator": req.userData.userId}); -} catch (err) { - console.error(err); - const error = new HttpError( - 'Could not add recipe to favorites. Try again later.', - 500 - ); - return next(error); -} - -if (existingRecipe) { - const error = new HttpError( - 'Recipe with this name exists already.', - 422 - ); - return next(error); -} - -try { - const sess = await mongoose.startSession(); - sess.startTransaction(); - await createdRecipe.save({ session: sess }); - user.recipes.push(createdRecipe); - await user.save({ session: sess }); - await sess.commitTransaction(); -} catch (err) { - console.error(err); - const error = new HttpError( - 'Creating recipe failed, please try again.Could not add recipe to favorites. Try again later.', - ); - return next(error); -} - -res.status(201).json({ recipe: createdRecipe }); + const { recipe } = req.body; + const parsedRecipe = JSON.parse(recipe); + + const createdRecipe = new Recipe({ + recipe: parsedRecipe, + image: req.image ? req.image.url : null, + creator: req.userData.userId + }); + + let user; + try { + user = await User.findById(req.userData.userId); + } catch (err) { + console.error(err); + const error = new HttpError('Could not add recipe to favorites. Try again later.', 500); + return next(error); + } + + if (!user) { + console.error('Could not find user by id.'); + const error = new HttpError('Could not add recipe to favorites. Try again later.', 404); + return next(error); + } + + let existingRecipe + try { + existingRecipe = await Recipe.findOne({ "recipe.name": parsedRecipe.name, "creator": req.userData.userId}); + } catch (err) { + console.error(err); + const error = new HttpError( + 'Could not add recipe to favorites. Try again later.', + 500 + ); + return next(error); + } + + if (existingRecipe) { + const error = new HttpError( + 'Recipe with this name exists already.', + 422 + ); + return next(error); + } + + try { + const sess = await mongoose.startSession(); + sess.startTransaction(); + await createdRecipe.save({ session: sess }); + user.recipes.push(createdRecipe); + await user.save({ session: sess }); + await sess.commitTransaction(); + } catch (err) { + console.error(err); + const error = new HttpError( + 'Creating recipe failed, please try again.Could not add recipe to favorites. Try again later.', + ); + return next(error); + } + + res.status(201).json({ recipe: createdRecipe }); }; const updateRecipe = async (req, res, next) => { -const { recipeString } = req.body; -const updatedRecipe = JSON.parse(recipeString); - -const undatedImage = req.image ? req.image.url : null; -const recipeId = req.params.pid; - -let recipe; -try { - recipe = await Recipe.findById(recipeId,); -} catch (err) { - console.error(err); - const error = new HttpError( - 'Could not update recipe in favorites. Try again later.', - 500 - ); - return next(error); -} - -if (!recipe) { - console.error('Could not find recipe by id.'); - const error = new HttpError('Could not update recipe in favorites. Try again later.', 404); - return next(error); -} - -if (recipe.creator.toString() !== req.userData.userId) { - console.error('Not authorized.'); - const error = new HttpError('You are not allowed to edit this recipe.', 401); - return next(error); -} - - -recipe.recipe = updatedRecipe; -// if(undatedImage) { -// fs.unlink(recipe.image, err => { -// console.log(err); -// }); -// recipe.image = undatedImage; -// } - -try { - await recipe.save(); -} catch (err) { - console.error(err); - const error = new HttpError( - 'Could not update recipe in favorites. Try again later.', - 500 - ); - return next(error); -} - -res.status(200).json({ recipe: recipe.toObject({ getters: true }) }); + const { recipeString } = req.body; + const updatedRecipe = JSON.parse(recipeString); + + const updatedImage = req.image ? req.image.url : null; + const recipeId = req.params.pid; + + let recipe; + try { + recipe = await Recipe.findById(recipeId,); + } catch (err) { + console.error(err); + const error = new HttpError( + 'Could not update recipe in favorites. Try again later.', + 500 + ); + return next(error); + } + + if (!recipe) { + console.error('Could not find recipe by id.'); + const error = new HttpError('Could not update recipe in favorites. Try again later.', 404); + return next(error); + } + + if (recipe.creator.toString() !== req.userData.userId) { + console.error('Not authorized.'); + const error = new HttpError('You are not allowed to edit this recipe.', 401); + return next(error); + } + + + recipe.recipe = updatedRecipe; + if(updatedImage) { + // fs.unlink(recipe.image, err => { + // console.log(err); + // }); + recipe.image = updatedImage; + } + + try { + await recipe.save(); + } catch (err) { + console.error(err); + const error = new HttpError( + 'Could not update recipe in favorites. Try again later.', + 500 + ); + return next(error); + } + + res.status(200).json({ recipe: recipe.toObject({ getters: true }) }); }; const deleteRecipe = async (req, res, next) => { -const recipeId = req.params.pid; - -let recipe; -try { - recipe = await Recipe.findById(recipeId).populate('creator'); -} catch (err) { - console.error(err); - const error = new HttpError( - 'Could not delete recipe. Try again later.', - 500 - ); - return next(error); -} - -if (!recipe) { - console.error('Could not find recipe by id.'); - const error = new HttpError('Could not delete recipe. Try again later.', 404); - return next(error); -} - -if (recipe.creator.id !== req.userData.userId) { - console.error('Not authorized.'); - const error = new HttpError( - 'You are not allowed to delete this recipe.', - 401 - ); - return next(error); -} - -const imagePath = recipe.image; - -try { - const sess = await mongoose.startSession(); - sess.startTransaction(); - await recipe.deleteOne({ session: sess }); - recipe.creator.recipes.pull(recipe); - await recipe.creator.save({ session: sess }); - await sess.commitTransaction(); -} catch (err) { - console.error(err); - const error = new HttpError( - 'Could not delete recipe. Try again later.', - 500 - ); - return next(error); -} - -// if(recipe.image) fs.unlink(imagePath, err => { -// console.log(err); -// }); - -res.status(200).json({ message: 'Deleted recipe.' }); + const recipeId = req.params.pid; + + let recipe; + try { + recipe = await Recipe.findById(recipeId).populate('creator'); + } catch (err) { + console.error(err); + const error = new HttpError( + 'Could not delete recipe. Try again later.', + 500 + ); + return next(error); + } + + if (!recipe) { + console.error('Could not find recipe by id.'); + const error = new HttpError('Could not delete recipe. Try again later.', 404); + return next(error); + } + + if (recipe.creator.id !== req.userData.userId) { + console.error('Not authorized.'); + const error = new HttpError( + 'You are not allowed to delete this recipe.', + 401 + ); + return next(error); + } + + // const imagePath = recipe.image; + + try { + const sess = await mongoose.startSession(); + sess.startTransaction(); + await recipe.deleteOne({ session: sess }); + recipe.creator.recipes.pull(recipe); + await recipe.creator.save({ session: sess }); + await sess.commitTransaction(); + } catch (err) { + console.error(err); + const error = new HttpError( + 'Could not delete recipe. Try again later.', + 500 + ); + return next(error); + } + + // if(recipe.image) fs.unlink(imagePath, err => { + // console.log(err); + // }); + + res.status(200).json({ message: 'Deleted recipe.' }); }; exports.getRecipes = getRecipes; diff --git a/functions/db-controllers/users-controllers.js b/functions/db-controllers/users-controllers.js index 28364ce..650272e 100644 --- a/functions/db-controllers/users-controllers.js +++ b/functions/db-controllers/users-controllers.js @@ -6,153 +6,153 @@ const jwt = require('jsonwebtoken'); const signup = async (req, res, next) => { -const errors = validationResult(req); -if (!errors.isEmpty()) { - console.error('Validation failed.'); - return next( - new HttpError('Invalid inputs passed, please check your data.', 422) - ); -} - -const { name, email, password } = req.body; - -let existingUser -try { - existingUser = await User.findOne({ email: email }) -} catch (err) { - console.error(err); - const error = new HttpError( - 'Signing up failed, please try again later.', - 500 - ); - return next(error); -} - -if (existingUser) { - const error = new HttpError( - 'User exists already, please login instead.', - 422 - ); - return next(error); -} - -let hashedPassword; -try { - hashedPassword = await bcrypt.hash(password, 12); -} catch (err) { - console.error(err); - const error = new HttpError( - 'Could not create user, please try again.', - 500 - ); - return next(error); -} - -const createdUser = new User({ - name, - email, - password: hashedPassword, - foods: [] -}); - -try { - await createdUser.save(); -} catch (err) { - console.error(err); - const error = new HttpError( - 'Signing up failed, please try again.', - 500 - ); - return next(error); -} - -let token; -try { - token = jwt.sign( - { userId: createdUser.id, email: createdUser.email }, - 'supersecret_dont_share', - { expiresIn: '1h' } - ); -} catch (err) { - console.error(err); - const error = new HttpError( - 'Signing up failed, please try again later.', - 500 - ); - return next(error); -} - -res - .status(201) - .json({ userId: createdUser.id, email: createdUser.email, token: token }); + const errors = validationResult(req); + if (!errors.isEmpty()) { + console.error('Validation failed.'); + return next( + new HttpError('Invalid inputs passed, please check your data.', 422) + ); + } + + const { name, email, password } = req.body; + + let existingUser + try { + existingUser = await User.findOne({ email: email }) + } catch (err) { + console.error(err); + const error = new HttpError( + 'Signing up failed, please try again later.', + 500 + ); + return next(error); + } + + if (existingUser) { + const error = new HttpError( + 'User exists already, please login instead.', + 422 + ); + return next(error); + } + + let hashedPassword; + try { + hashedPassword = await bcrypt.hash(password, 12); + } catch (err) { + console.error(err); + const error = new HttpError( + 'Could not create user, please try again.', + 500 + ); + return next(error); + } + + const createdUser = new User({ + name, + email, + password: hashedPassword, + foods: [] + }); + + try { + await createdUser.save(); + } catch (err) { + console.error(err); + const error = new HttpError( + 'Signing up failed, please try again.', + 500 + ); + return next(error); + } + + let token; + try { + token = jwt.sign( + { userId: createdUser.id, email: createdUser.email }, + 'supersecret_dont_share', + { expiresIn: '1h' } + ); + } catch (err) { + console.error(err); + const error = new HttpError( + 'Signing up failed, please try again later.', + 500 + ); + return next(error); + } + + res + .status(201) + .json({ userId: createdUser.id, email: createdUser.email, token: token }); }; const login = async (req, res, next) => { -const { email, password } = req.body; - -let existingUser; - -try { - existingUser = await User.findOne({ email: email }) -} catch (err) { - console.error(err); - const error = new HttpError( - 'Logging in failed, please try again later.', - 500 - ); - return next(error); -} - -if (!existingUser) { - console.error('Could not find user by email.'); - const error = new HttpError( - 'Invalid credentials, could not log you in.', - 401 - ); - return next(error); -} - -let isValidPassword = false; -try { - isValidPassword = await bcrypt.compare(password, existingUser.password); -} catch (err) { - console.error(err); - const error = new HttpError( - 'Could not log you in, please check your credentials and try again.', - 500 - ); - return next(error); -} - -if (!isValidPassword) { - const error = new HttpError( - 'Invalid password, could not log you in.', - 401 - ); - return next(error); -} - -let token; -try { - token = jwt.sign( - { userId: existingUser.id, email: existingUser.email }, - 'supersecret_dont_share', - { expiresIn: '1h' } - ); -} catch (err) { - console.error(err); - const error = new HttpError( - 'Logging in failed, please try again later.', - 500 - ); - return next(error); -} - -res.json({ - userId: existingUser.id, - email: existingUser.email, - token: token -}); + const { email, password } = req.body; + + let existingUser; + + try { + existingUser = await User.findOne({ email: email }) + } catch (err) { + console.error(err); + const error = new HttpError( + 'Logging in failed, please try again later.', + 500 + ); + return next(error); + } + + if (!existingUser) { + console.error('Could not find user by email.'); + const error = new HttpError( + 'Invalid credentials, could not log you in.', + 401 + ); + return next(error); + } + + let isValidPassword = false; + try { + isValidPassword = await bcrypt.compare(password, existingUser.password); + } catch (err) { + console.error(err); + const error = new HttpError( + 'Could not log you in, please check your credentials and try again.', + 500 + ); + return next(error); + } + + if (!isValidPassword) { + const error = new HttpError( + 'Invalid password, could not log you in.', + 401 + ); + return next(error); + } + + let token; + try { + token = jwt.sign( + { userId: existingUser.id, email: existingUser.email }, + 'supersecret_dont_share', + { expiresIn: '1h' } + ); + } catch (err) { + console.error(err); + const error = new HttpError( + 'Logging in failed, please try again later.', + 500 + ); + return next(error); + } + + res.json({ + userId: existingUser.id, + email: existingUser.email, + token: token + }); }; exports.signup = signup; diff --git a/functions/middleware/check-auth.js b/functions/middleware/check-auth.js index 329cde4..fc06436 100644 --- a/functions/middleware/check-auth.js +++ b/functions/middleware/check-auth.js @@ -7,17 +7,17 @@ module.exports = (req, res, next) => { return next(); } - try { - const token = req.headers.authorization.split(' ')[1]; // Authorization: 'Bearer TOKEN' - if (!token) { - throw new Error('Logging in failed, please try again later.'); - } - const decodedToken = jwt.verify(token, 'supersecret_dont_share'); - req.userData = { userId: decodedToken.userId }; - next(); - } catch (err) { - console.error(err); - const error = new HttpError('Logging in failed, please try again later.', 401); - return next(error); - } + try { + const token = req.headers.authorization.split(' ')[1]; // Authorization: 'Bearer TOKEN' + if (!token) { + throw new Error('Logging in failed, please try again later.'); + } + const decodedToken = jwt.verify(token, 'supersecret_dont_share'); + req.userData = { userId: decodedToken.userId }; + next(); + } catch (err) { + console.error(err); + const error = new HttpError('Logging in failed, please try again later.', 401); + return next(error); + } }; \ No newline at end of file