Migrated to CommonJS

This commit is contained in:
2020-10-08 11:12:56 +02:00
parent 871919c838
commit 10a7680d90
16 changed files with 189 additions and 129 deletions

View File

@@ -1,4 +1,4 @@
export default function makeResetPassMessage(link) { function makeResetPassMessage(link) {
return { return {
html: `<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> html: `<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"> <html xmlns="http://www.w3.org/1999/xhtml">
@@ -146,3 +146,5 @@ export default function makeResetPassMessage(link) {
text: `Drogi użytkowniku, dostałeś tę wiadomość, ponieważ użyłeś opcji "Nie pamiętam hasła" w aplikacji Menui. Twoje tymczasowe hasło to: ${link}. Zaloguj się za jego pomocą i ustaw nowe bezpieczne hasło. Jeżeli nie wysyłałeś prośby o zmianę hasła, prosimy zignoruj tę wiadomość. Pozdrawiamy - Zespół Menui`, text: `Drogi użytkowniku, dostałeś tę wiadomość, ponieważ użyłeś opcji "Nie pamiętam hasła" w aplikacji Menui. Twoje tymczasowe hasło to: ${link}. Zaloguj się za jego pomocą i ustaw nowe bezpieczne hasło. Jeżeli nie wysyłałeś prośby o zmianę hasła, prosimy zignoruj tę wiadomość. Pozdrawiamy - Zespół Menui`,
}; };
} }
module.exports = makeResetPassMessage;

View File

@@ -1,4 +1,4 @@
import mongoose from "mongoose"; const mongoose = require("mongoose");
const dishSchema = mongoose.Schema({ const dishSchema = mongoose.Schema({
_id: mongoose.Types.ObjectId, _id: mongoose.Types.ObjectId,
@@ -43,4 +43,4 @@ const dishSchema = mongoose.Schema({
vegetarian: Boolean, vegetarian: Boolean,
}); });
export default mongoose.model("Dish", dishSchema); module.exports = mongoose.model("Dish", dishSchema);

View File

@@ -1,4 +1,4 @@
import mongoose from "mongoose"; const mongoose = require("mongoose");
const paymentSchema = mongoose.Schema({ const paymentSchema = mongoose.Schema({
_id: mongoose.Types.ObjectId, _id: mongoose.Types.ObjectId,
@@ -7,4 +7,4 @@ const paymentSchema = mongoose.Schema({
months: Number, months: Number,
}); });
export default mongoose.model("Payment", paymentSchema); module.exorts = mongoose.model("Payment", paymentSchema);

View File

@@ -1,4 +1,4 @@
import mongoose from "mongoose"; const mongoose = require("mongoose");
const restaurantSchema = mongoose.Schema({ const restaurantSchema = mongoose.Schema({
_id: mongoose.Types.ObjectId, _id: mongoose.Types.ObjectId,
@@ -75,4 +75,4 @@ const restaurantSchema = mongoose.Schema({
dishes: [mongoose.Types.ObjectId], dishes: [mongoose.Types.ObjectId],
}); });
export default mongoose.model("Restaurant", restaurantSchema); module.exports = mongoose.model("Restaurant", restaurantSchema);

View File

@@ -1,4 +1,4 @@
import mongoose from "mongoose"; const mongoose = require("mongoose");
const userSchema = mongoose.Schema({ const userSchema = mongoose.Schema({
_id: mongoose.Types.ObjectId, _id: mongoose.Types.ObjectId,
@@ -41,4 +41,4 @@ const userSchema = mongoose.Schema({
trialUsed: Boolean, trialUsed: Boolean,
}); });
export default mongoose.model("User", userSchema); module.exports = mongoose.model("User", userSchema);

View File

@@ -1,19 +1,19 @@
import express from "express"; const express = require("express");
import { createDish } from "../services/dataPrepServices.js"; const { createDish } = require("../services/dataPrepServices.js");
import { const {
removeDish, removeDish,
fetchDish, fetchDish,
addDishToRestaurant, addDishToRestaurant,
setDishVisibility, setDishVisibility,
} from "../services/databaseServices.js"; } = require("../services/databaseServices.js");
import { const {
validateRestaurant, validateRestaurant,
validateUserToken, validateUserToken,
validateDishId, validateDishId,
handleError, handleError,
verifyDishAccess, verifyDishAccess,
} from "../services/services.js"; } = require("../services/services.js");
import Dish from "../models/dish.js"; const Dish = require("../models/dish.js");
var router = express.Router(); var router = express.Router();
@@ -89,4 +89,4 @@ router.put("/", async (req, res) => {
} }
}); });
export default router; module.exports = router;

View File

@@ -1,8 +1,8 @@
import express from "express"; const express = require("express");
import * as services from "../services/services.js"; const { validateUserToken, handleError } = require("../services/services.js");
import { uploadBlob } from "../services/azureServices.js"; const { uploadBlob } = require("../services/azureServices.js");
// Azure // Azure
import multer from "multer"; const multer = require("multer");
var router = express.Router(); var router = express.Router();
var storage = multer.memoryStorage(); var storage = multer.memoryStorage();
@@ -22,11 +22,11 @@ const uploadStrategy = multer({
router.post("/", uploadStrategy, async (req, res) => { router.post("/", uploadStrategy, async (req, res) => {
try { try {
const token = req.headers["x-auth-token"]; const token = req.headers["x-auth-token"];
services.validateUserToken(token); validateUserToken(token);
await uploadBlob(req, res); await uploadBlob(req, res);
} catch (error) { } catch (error) {
services.handleError(error, res); handleError(error, res);
} }
}); });
export default router; module.exports = router;

View File

@@ -1,5 +1,5 @@
import express from "express"; const express = require("express");
import { handleError } from "../services/services.js"; const { handleError } = require("../services/services.js");
var router = express.Router(); var router = express.Router();
@@ -11,4 +11,4 @@ router.post("/", async (req, res) => {
} }
}); });
export default router; module.exports = router;

View File

@@ -1,6 +1,6 @@
import express from "express"; const express = require("express");
import { createRestaurant } from "../services/dataPrepServices.js"; const { createRestaurant } = require("../services/dataPrepServices.js");
import { const {
addRestaurantToUser, addRestaurantToUser,
fetchRestaurant, fetchRestaurant,
fetchAllDishesForRestaurant, fetchAllDishesForRestaurant,
@@ -11,8 +11,8 @@ import {
fetchUser, fetchUser,
initializePayment, initializePayment,
renewSubscription, renewSubscription,
} from "../services/databaseServices.js"; } = require("../services/databaseServices.js");
import { const {
decodeAndSanitize, decodeAndSanitize,
validateRestaurant, validateRestaurant,
handleError, handleError,
@@ -20,8 +20,8 @@ import {
verifyRestaurantAccess, verifyRestaurantAccess,
newError, newError,
checkPassword, checkPassword,
} from "../services/services.js"; } = require("../services/services.js");
import Restaurant from "../models/restaurant.js"; const Restaurant = require("../models/restaurant.js");
var router = express.Router(); var router = express.Router();
@@ -180,4 +180,4 @@ router.post("/subscription", async (req, res) => {
} }
}); });
export default router; module.exports = router;

View File

@@ -1,7 +1,7 @@
import express from "express"; const express = require("express");
import Restaurant from "../models/restaurant.js"; const Restaurant = require("../models/restaurant.js");
import sanitizer from "string-sanitizer"; const sanitizer = require("string-sanitizer");
import { handleError } from "../services/services.js"; const { handleError } = require("../services/services.js");
var router = express.Router(); var router = express.Router();
@@ -89,4 +89,4 @@ router.get("/autocomplete/", (req, res) => {
} }
}); });
export default router; module.exports = router;

View File

@@ -1,7 +1,13 @@
import express from "express"; const express = require("express");
import { changeUserPass, fetchUser } from "../services/databaseServices.js"; const {
import { createUser, prepareSafeUser } from "../services/dataPrepServices.js"; changeUserPass,
import { fetchUser,
} = require("../services/databaseServices.js");
const {
createUser,
prepareSafeUser,
} = require("../services/dataPrepServices.js");
const {
newError, newError,
handleError, handleError,
checkPassword, checkPassword,
@@ -9,8 +15,8 @@ import {
checkEmailTaken, checkEmailTaken,
validateUserToken, validateUserToken,
hashPass, hashPass,
} from "../services/services.js"; } = require("../services/services.js");
import { resetPassword } from "../services/mailServices.js"; const { resetPassword } = require("../services/mailServices.js");
var router = express.Router(); var router = express.Router();
@@ -101,4 +107,4 @@ router.post("/resetpass", async (req, res) => {
} }
}); });
export default router; module.exports = router;

View File

@@ -1,7 +1,6 @@
import azureBlob from "@azure/storage-blob"; const azureBlob = require("@azure/storage-blob");
import e from "express"; const getStream = require("into-stream");
import getStream from "into-stream"; const { newError } = require("./services.js");
import { newError } from "./services.js";
// SETUP // SETUP
const containerURL = `https://${process.env.AZURE_STORAGE_ACCOUNT_NAME}.blob.core.windows.net/img/`; const containerURL = `https://${process.env.AZURE_STORAGE_ACCOUNT_NAME}.blob.core.windows.net/img/`;
@@ -19,7 +18,7 @@ const blobServiceClient = new azureBlob.BlobServiceClient(
); );
// CODE // CODE
export async function renameBlob(blobURL) { async function renameBlob(blobURL) {
try { try {
const blobName = blobURL.replace(containerURL, ""); const blobName = blobURL.replace(containerURL, "");
const containerClient = blobServiceClient.getContainerClient(container); const containerClient = blobServiceClient.getContainerClient(container);
@@ -33,7 +32,7 @@ export async function renameBlob(blobURL) {
} }
} }
export async function uploadBlob(request, resp) { async function uploadBlob(request, resp) {
const blobName = makeTempBlobName(request.file.originalname); const blobName = makeTempBlobName(request.file.originalname);
const stream = getStream(request.file.buffer); const stream = getStream(request.file.buffer);
const containerClient = blobServiceClient.getContainerClient(container); const containerClient = blobServiceClient.getContainerClient(container);
@@ -60,24 +59,24 @@ export async function uploadBlob(request, resp) {
} }
} }
export function removePrefix(string) { function removePrefix(string) {
const newString = string.replace("TEMP_", ""); const newString = string.replace("TEMP_", "");
return newString; return newString;
} }
export function makeTempBlobName(originalName) { function makeTempBlobName(originalName) {
const identifier = Math.random().toString().replace(/0\./, ""); const identifier = Math.random().toString().replace(/0\./, "");
return `TEMP_${identifier}-${originalName}`; return `TEMP_${identifier}-${originalName}`;
} }
export function setDeleteTempBlobTimer(blobName, containerClient, minutes) { function setDeleteTempBlobTimer(blobName, containerClient, minutes) {
let blob = containerClient.getBlobClient(blobName); let blob = containerClient.getBlobClient(blobName);
setTimeout(() => { setTimeout(() => {
blob.delete(); blob.delete();
}, 1000 * 60 * minutes); }, 1000 * 60 * minutes);
} }
export async function deleteImage(url) { async function deleteImage(url) {
if (!url || url === "" || url === "empty") { if (!url || url === "" || url === "empty") {
return; return;
} else { } else {
@@ -93,3 +92,10 @@ export async function deleteImage(url) {
} }
} }
} }
exports.renameBlob = renameBlob;
exports.uploadBlob = uploadBlob;
exports.removePrefix = removePrefix;
exports.makeTempBlobName = makeTempBlobName;
exports.setDeleteTempBlobTimer = setDeleteTempBlobTimer;
exports.deleteImage = deleteImage;

View File

@@ -1,13 +1,13 @@
import { hashPass, newError, saveImage } from "./services.js"; const { hashPass, newError, saveImage } = require("./services.js");
import sanitizer from "string-sanitizer"; const sanitizer = require("string-sanitizer");
import mongoose from "mongoose"; const mongoose = require("mongoose");
import Dish from "../models/dish.js"; const Dish = require("../models/dish.js");
import User from "../models/users.js"; const User = require("../models/users.js");
import Restaurant from "../models/restaurant.js"; const Restaurant = require("../models/restaurant.js");
import { fetchMultipleRestaurants } from "./databaseServices.js"; const { fetchMultipleRestaurants } = require("./databaseServices.js");
import { deleteImage } from "./azureServices.js"; const { deleteImage } = require("./azureServices.js");
export async function createUser(request) { async function createUser(request) {
const password = await hashPass(request.body.password); const password = await hashPass(request.body.password);
const user = new User({ const user = new User({
_id: new mongoose.Types.ObjectId(), _id: new mongoose.Types.ObjectId(),
@@ -47,7 +47,7 @@ async function handleImageUpdate(request, previous) {
} }
} }
export async function createRestaurant(request, oldRestaurant) { async function createRestaurant(request, oldRestaurant) {
try { try {
if (!oldRestaurant) { if (!oldRestaurant) {
const img = await handleImageUpdate(request); const img = await handleImageUpdate(request);
@@ -105,7 +105,7 @@ export async function createRestaurant(request, oldRestaurant) {
} }
} }
export async function prepareSafeUser(user) { async function prepareSafeUser(user) {
const restaurants = await fetchMultipleRestaurants(user.restaurants); const restaurants = await fetchMultipleRestaurants(user.restaurants);
const safeUser = { const safeUser = {
firstname: user.firstname, firstname: user.firstname,
@@ -120,7 +120,7 @@ export async function prepareSafeUser(user) {
return safeUser; return safeUser;
} }
export async function createDish(dish, restaurantId, oldDish) { async function createDish(dish, restaurantId, oldDish) {
try { try {
if (!oldDish) { if (!oldDish) {
const img = await handleImageUpdate(dish); const img = await handleImageUpdate(dish);
@@ -166,7 +166,7 @@ export async function createDish(dish, restaurantId, oldDish) {
} }
} }
export function appendDishToLunchSet(lunchMenu, setName, dishId) { function appendDishToLunchSet(lunchMenu, setName, dishId) {
const result = lunchMenu.map((lunchSet) => { const result = lunchMenu.map((lunchSet) => {
if (lunchSet.lunchSetName === setName) { if (lunchSet.lunchSetName === setName) {
let updatedSet = lunchSet; let updatedSet = lunchSet;
@@ -179,7 +179,7 @@ export function appendDishToLunchSet(lunchMenu, setName, dishId) {
return result; return result;
} }
export function removeDishFromLunchSet(lunchMenu, setName, dishId) { function removeDishFromLunchSet(lunchMenu, setName, dishId) {
const result = lunchMenu.map((lunchSet) => { const result = lunchMenu.map((lunchSet) => {
if (lunchSet.lunchSetName === setName) { if (lunchSet.lunchSetName === setName) {
let updatedSet = lunchSet; let updatedSet = lunchSet;
@@ -194,3 +194,10 @@ export function removeDishFromLunchSet(lunchMenu, setName, dishId) {
}); });
return result; return result;
} }
exports.createUser = createUser;
exports.createRestaurant = createRestaurant;
exports.prepareSafeUser = prepareSafeUser;
exports.createDish = createDish;
exports.appendDishToLunchSet = appendDishToLunchSet;
exports.removeDishFromLunchSet = removeDishFromLunchSet;

View File

@@ -1,24 +1,24 @@
import Restaurant from "../models/restaurant.js"; const Restaurant = require("../models/restaurant.js");
import Dish from "../models/dish.js"; const Dish = require("../models/dish.js");
import User from "../models/users.js"; const User = require("../models/users.js");
import Payments from "../models/payments.js"; const Payments = require("../models/payments.js");
import { deleteImage } from "./azureServices.js"; const { deleteImage } = require("./azureServices.js");
import { const {
appendDishToLunchSet, appendDishToLunchSet,
removeDishFromLunchSet, removeDishFromLunchSet,
} from "./dataPrepServices.js"; } = require("./dataPrepServices.js");
import { newError } from "./services.js"; const { newError } = require("./services.js");
import mongoose from "mongoose"; const mongoose = require("mongoose");
import axios from "axios"; const axios = require("axios");
import crypto from "crypto"; const crypto = require("crypto");
export async function changeUserPass(userId, newPass) { async function changeUserPass(userId, newPass) {
User.findByIdAndUpdate(userId, { $set: { password: newPass } }).catch((e) => { User.findByIdAndUpdate(userId, { $set: { password: newPass } }).catch((e) => {
throw newError("Zmiana hasła nie powiodła się.", 500); throw newError("Zmiana hasła nie powiodła się.", 500);
}); });
} }
export async function removeDish(dishId) { async function removeDish(dishId) {
const deletedDoc = await Dish.findByIdAndDelete(dishId).catch((e) => { const deletedDoc = await Dish.findByIdAndDelete(dishId).catch((e) => {
throw newError("Usunięcie dania nie powiodło się.", 500); throw newError("Usunięcie dania nie powiodło się.", 500);
}); });
@@ -30,7 +30,7 @@ export async function removeDish(dishId) {
}); });
} }
export async function removeRestaurant(restaurantId, userId) { async function removeRestaurant(restaurantId, userId) {
const deletedDoc = await Restaurant.findByIdAndDelete(restaurantId).catch( const deletedDoc = await Restaurant.findByIdAndDelete(restaurantId).catch(
(e) => { (e) => {
throw newError("Usunięcie nie powiodło się.", 500); throw newError("Usunięcie nie powiodło się.", 500);
@@ -53,7 +53,7 @@ export async function removeRestaurant(restaurantId, userId) {
}); });
} }
export async function addDishToRestaurant(restaurantId, dishId) { async function addDishToRestaurant(restaurantId, dishId) {
await Restaurant.updateOne( await Restaurant.updateOne(
{ _id: restaurantId }, { _id: restaurantId },
{ $push: { dishes: dishId } } { $push: { dishes: dishId } }
@@ -62,7 +62,7 @@ export async function addDishToRestaurant(restaurantId, dishId) {
}); });
} }
export async function addRestaurantToUser(user, restaurant) { async function addRestaurantToUser(user, restaurant) {
await User.findByIdAndUpdate(user.id, { await User.findByIdAndUpdate(user.id, {
$push: { restaurants: restaurant._id }, $push: { restaurants: restaurant._id },
}).catch((e) => { }).catch((e) => {
@@ -100,7 +100,7 @@ function startDate(restaurant) {
} }
} }
export async function renewSubscription(restaurantId, monthsToAdd) { async function renewSubscription(restaurantId, monthsToAdd) {
const restaurant = await Restaurant.findById(restaurantId).catch((err) => { const restaurant = await Restaurant.findById(restaurantId).catch((err) => {
throw newError("Nie udało się pobrać restauracji.", 404); throw newError("Nie udało się pobrać restauracji.", 404);
}); });
@@ -150,7 +150,7 @@ async function checkIfAlreadyInSet(restaurant, setName, dishId) {
} }
} }
export async function changeCategory(restaurantId, categoryName, action) { async function changeCategory(restaurantId, categoryName, action) {
if (action === "add") { if (action === "add") {
const restaurant = await Restaurant.findById(restaurantId).catch((err) => { const restaurant = await Restaurant.findById(restaurantId).catch((err) => {
throw newError("Nie udało się pobrać restauracji.", 404); throw newError("Nie udało się pobrać restauracji.", 404);
@@ -172,7 +172,7 @@ export async function changeCategory(restaurantId, categoryName, action) {
} }
} }
export async function setDishVisibility(dishId, visible) { async function setDishVisibility(dishId, visible) {
await Dish.findByIdAndUpdate(dishId, { $set: { hidden: !visible } }).catch( await Dish.findByIdAndUpdate(dishId, { $set: { hidden: !visible } }).catch(
(e) => { (e) => {
throw newError("Nie udało się zmienić dania.", 500); throw newError("Nie udało się zmienić dania.", 500);
@@ -180,7 +180,7 @@ export async function setDishVisibility(dishId, visible) {
); );
} }
export async function changeLunchMenuSet(restaurantId, action, lunchSet) { async function changeLunchMenuSet(restaurantId, action, lunchSet) {
if (action === "add") { if (action === "add") {
const restaurant = await Restaurant.findById(restaurantId).catch((err) => { const restaurant = await Restaurant.findById(restaurantId).catch((err) => {
throw newError("Nie udało się pobrać restauracji.", 404); throw newError("Nie udało się pobrać restauracji.", 404);
@@ -202,7 +202,7 @@ export async function changeLunchMenuSet(restaurantId, action, lunchSet) {
} }
} }
export async function changeLunchMenu(restaurantId, setName, dishId, action) { async function changeLunchMenu(restaurantId, setName, dishId, action) {
if (action === "add") { if (action === "add") {
const restaurant = await Restaurant.findById(restaurantId).catch((err) => { const restaurant = await Restaurant.findById(restaurantId).catch((err) => {
throw newError("Nie udało się pobrać restauracji.", 404); throw newError("Nie udało się pobrać restauracji.", 404);
@@ -237,14 +237,14 @@ export async function changeLunchMenu(restaurantId, setName, dishId, action) {
} }
} }
export async function fetchRestaurant(id) { async function fetchRestaurant(id) {
const data = await Restaurant.findById(id).catch((e) => { const data = await Restaurant.findById(id).catch((e) => {
throw newError("Nie udało się pobrać restauracji.", 500); throw newError("Nie udało się pobrać restauracji.", 500);
}); });
return data; return data;
} }
export async function fetchMultipleRestaurants(idArray) { async function fetchMultipleRestaurants(idArray) {
let data = []; let data = [];
for (const id of idArray) { for (const id of idArray) {
let response = await fetchRestaurant(id); let response = await fetchRestaurant(id);
@@ -253,7 +253,7 @@ export async function fetchMultipleRestaurants(idArray) {
return data; return data;
} }
export async function fetchAllDishesForRestaurant(restaurant) { async function fetchAllDishesForRestaurant(restaurant) {
let dishes = []; let dishes = [];
for (const dish of restaurant.dishes) { for (const dish of restaurant.dishes) {
let res = await fetchDish(dish._id); let res = await fetchDish(dish._id);
@@ -262,14 +262,14 @@ export async function fetchAllDishesForRestaurant(restaurant) {
return dishes; return dishes;
} }
export async function fetchDish(id) { async function fetchDish(id) {
let data = await Dish.findById(id).catch((e) => { let data = await Dish.findById(id).catch((e) => {
throw newError(`Nie udało się pobrać ${id}`, 404); throw newError(`Nie udało się pobrać ${id}`, 404);
}); });
return data; return data;
} }
export async function fetchUser(email) { async function fetchUser(email) {
if (!email) throw newError("Brak danych", 204); if (!email) throw newError("Brak danych", 204);
const user = await User.findOne({ email: email }); const user = await User.findOne({ email: email });
if (!user) throw newError("Użytkownik nie istnieje", 404); if (!user) throw newError("Użytkownik nie istnieje", 404);
@@ -325,7 +325,7 @@ async function registerTransaction(paymentInfo, userData) {
return response; return response;
} }
export async function initializePayment(restaurantId, userData, type) { async function initializePayment(restaurantId, userData, type) {
const newPayment = new Payments({ const newPayment = new Payments({
_id: new mongoose.Types.ObjectId(), _id: new mongoose.Types.ObjectId(),
restaurantId: restaurantId, restaurantId: restaurantId,
@@ -336,3 +336,20 @@ export async function initializePayment(restaurantId, userData, type) {
newPayment.save(); newPayment.save();
return payment; return payment;
} }
exports.changeUserPass = changeUserPass;
exports.removeDish = removeDish;
exports.removeRestaurant = removeRestaurant;
exports.addDishToRestaurant = addDishToRestaurant;
exports.addRestaurantToUser = addRestaurantToUser;
exports.renewSubscription = renewSubscription;
exports.changeCategory = changeCategory;
exports.setDishVisibility = setDishVisibility;
exports.changeLunchMenuSet = changeLunchMenuSet;
exports.changeLunchMenu = changeLunchMenu;
exports.fetchRestaurant = fetchRestaurant;
exports.fetchMultipleRestaurants = fetchMultipleRestaurants;
exports.fetchAllDishesForRestaurant = fetchAllDishesForRestaurant;
exports.fetchDish = fetchDish;
exports.fetchUser = fetchUser;
exports.initializePayment = initializePayment;

View File

@@ -1,8 +1,11 @@
import nodemailer from "nodemailer"; const nodemailer = require("nodemailer");
import path from "path"; const path = require("path");
import { MAIL_PASS } from "../config/index.js"; const { MAIL_PASS } = require("../config/index.js");
import makeResetPassMessage from "../config/mailTemplateReset.js"; const makeResetPassMessage = require("../config/mailTemplateReset.js");
import { newError, generatePasswordResetLink } from "../services/services.js"; const {
newError,
generatePasswordResetLink,
} = require("../services/services.js");
const images = path.resolve("images"); const images = path.resolve("images");
@@ -33,7 +36,7 @@ async function sendMail(reciever, subject, textMessage, htmlMessage) {
}); });
} }
export async function resetPassword(email) { async function resetPassword(email) {
const resetLink = generatePasswordResetLink(email); const resetLink = generatePasswordResetLink(email);
const message = makeResetPassMessage(resetLink); const message = makeResetPassMessage(resetLink);
await sendMail( await sendMail(
@@ -45,3 +48,5 @@ export async function resetPassword(email) {
throw newError("Nieznany błąd podczas resetu hasła", 500); throw newError("Nieznany błąd podczas resetu hasła", 500);
}); });
} }
exports.resetPassword = resetPassword;

View File

@@ -1,15 +1,14 @@
import Restaurant from "../models/restaurant.js"; const Restaurant = require("../models/restaurant.js");
import Dish from "../models/dish.js"; const Dish = require("../models/dish.js");
import User from "../models/users.js"; const User = require("../models/users.js");
import mongoose from "mongoose"; const mongoose = require("mongoose");
import sanitizer from "string-sanitizer"; const sanitizer = require("string-sanitizer");
import { renameBlob } from "./azureServices.js"; const { renameBlob } = require("./azureServices.js");
import jwt from "jsonwebtoken"; const jwt = require("jsonwebtoken");
import bcrypt from "bcrypt"; const bcrypt = require("bcrypt");
import * as config from "../config/index.js"; const { jwtSecret } = require("../config/index.js");
const { jwtSecret } = config;
export function newError(message, status) { function newError(message, status) {
const error = { const error = {
message: message, message: message,
status: status, status: status,
@@ -17,7 +16,7 @@ export function newError(message, status) {
return error; return error;
} }
export function handleError(error, responseObject) { function handleError(error, responseObject) {
if (!error.status) { if (!error.status) {
console.log(error); console.log(error);
responseObject.sendStatus(500); responseObject.sendStatus(500);
@@ -26,7 +25,7 @@ export function handleError(error, responseObject) {
} }
} }
export async function validateRestaurant(id) { async function validateRestaurant(id) {
if (!mongoose.Types.ObjectId.isValid(id)) if (!mongoose.Types.ObjectId.isValid(id))
throw newError("Nieprawidłowy ID", 204); throw newError("Nieprawidłowy ID", 204);
let valid = await Restaurant.exists({ _id: id }); let valid = await Restaurant.exists({ _id: id });
@@ -34,17 +33,17 @@ export async function validateRestaurant(id) {
return true; return true;
} }
export function decodeAndSanitize(query) { function decodeAndSanitize(query) {
if (!query) throw newError("Brak danych.", 204); if (!query) throw newError("Brak danych.", 204);
return sanitizer.sanitize.keepUnicode(decodeURI(query)); return sanitizer.sanitize.keepUnicode(decodeURI(query));
} }
export async function checkPassword(password, hash) { async function checkPassword(password, hash) {
const result = await bcrypt.compare(password, hash); const result = await bcrypt.compare(password, hash);
if (!result) throw newError("Hasło nieprawidłowe", 401); if (!result) throw newError("Hasło nieprawidłowe", 401);
} }
export function generateAuthToken(user) { function generateAuthToken(user) {
const token = jwt.sign( const token = jwt.sign(
{ {
email: user.email, email: user.email,
@@ -71,13 +70,15 @@ function generatePasswordResetToken(email) {
return token; return token;
} }
export function generatePasswordResetLink(email) { // SET FRONTEND URL HERE
function generatePasswordResetLink(email) {
const token = generatePasswordResetToken(email); const token = generatePasswordResetToken(email);
const link = `localhost:3000/resetpassword?token=${token}`; const link = `localhost:3000/resetpassword?token=${token}`;
return link; return link;
} }
export async function checkEmailTaken(email) { async function checkEmailTaken(email) {
if (!email) throw newError("Brak adresu email", 204); if (!email) throw newError("Brak adresu email", 204);
await User.exists({ email: email }).then((res) => { await User.exists({ email: email }).then((res) => {
if (res) { if (res) {
@@ -86,7 +87,7 @@ export async function checkEmailTaken(email) {
}); });
} }
export function validateUserToken(token) { function validateUserToken(token) {
if (!token) throw newError("Brak dostępu", 401); if (!token) throw newError("Brak dostępu", 401);
try { try {
const verified = jwt.verify(token, jwtSecret, { ignoreExpiration: false }); const verified = jwt.verify(token, jwtSecret, { ignoreExpiration: false });
@@ -97,7 +98,7 @@ export function validateUserToken(token) {
} }
} }
export async function validateDishId(id) { async function validateDishId(id) {
if (!mongoose.Types.ObjectId.isValid(id)) { if (!mongoose.Types.ObjectId.isValid(id)) {
throw newError("Niewłaściwy ID", 400); throw newError("Niewłaściwy ID", 400);
} }
@@ -105,7 +106,7 @@ export async function validateDishId(id) {
if (!dishDoesExist) throw newError("Te danie nie istnieje w bazie.", 404); if (!dishDoesExist) throw newError("Te danie nie istnieje w bazie.", 404);
} }
export async function verifyDishAccess(dishId, decodedToken) { async function verifyDishAccess(dishId, decodedToken) {
const fetch = await User.findById(decodedToken.id, "restaurants").catch( const fetch = await User.findById(decodedToken.id, "restaurants").catch(
(error) => { (error) => {
throw newError("Nie znaleziono użytkownika.", 500); throw newError("Nie znaleziono użytkownika.", 500);
@@ -119,7 +120,7 @@ export async function verifyDishAccess(dishId, decodedToken) {
if (!valid) throw newError("Nie masz dostępu do tego dania.", 401); if (!valid) throw newError("Nie masz dostępu do tego dania.", 401);
} }
export async function verifyRestaurantAccess(restaurantId, decodedToken) { async function verifyRestaurantAccess(restaurantId, decodedToken) {
const fetch = await User.findById(decodedToken.id, "restaurants").catch( const fetch = await User.findById(decodedToken.id, "restaurants").catch(
(error) => { (error) => {
throw newError("Nie znaleziono użytkownika.", 500); throw newError("Nie znaleziono użytkownika.", 500);
@@ -130,7 +131,7 @@ export async function verifyRestaurantAccess(restaurantId, decodedToken) {
if (!valid) throw newError("Nie masz dostępu do tej restauracji.", 401); if (!valid) throw newError("Nie masz dostępu do tej restauracji.", 401);
} }
export function yearFromNowDate() { function yearFromNowDate() {
Date.prototype.addDays = function (days) { Date.prototype.addDays = function (days) {
var date = new Date(this.valueOf()); var date = new Date(this.valueOf());
date.setDate(date.getDate() + days); date.setDate(date.getDate() + days);
@@ -140,7 +141,7 @@ export function yearFromNowDate() {
return date.addDays(365); return date.addDays(365);
} }
export async function hashPass(pass) { async function hashPass(pass) {
if (pass.length < 6) { if (pass.length < 6) {
throw newError("Hasło za krótkie.", 500); throw newError("Hasło za krótkie.", 500);
} }
@@ -153,7 +154,23 @@ export async function hashPass(pass) {
} }
} }
export async function saveImage(url) { async function saveImage(url) {
const newURL = await renameBlob(url); const newURL = await renameBlob(url);
return newURL; return newURL;
} }
exports.newError = newError;
exports.handleError = handleError;
exports.validateRestaurant = validateRestaurant;
exports.decodeAndSanitize = decodeAndSanitize;
exports.checkPassword = checkPassword;
exports.generateAuthToken = generateAuthToken;
exports.generatePasswordResetLink = generatePasswordResetLink;
exports.checkEmailTaken = checkEmailTaken;
exports.validateUserToken = validateUserToken;
exports.validateDishId = validateDishId;
exports.verifyDishAccess = verifyDishAccess;
exports.verifyRestaurantAccess = verifyRestaurantAccess;
exports.yearFromNowDate = yearFromNowDate;
exports.hashPass = hashPass;
exports.saveImage = saveImage;