Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Shadmaan Commit🍉 #280

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
145 changes: 75 additions & 70 deletions lib/auth.js
Original file line number Diff line number Diff line change
@@ -1,91 +1,96 @@
const ObjectId = require('mongodb').ObjectID;
const _ = require('lodash');
const ObjectId = require("mongodb");
const lodash = require("lodash");

const restrictedRoutes = [
{ route: '/admin/product/new', response: 'redirect' },
{ route: '/admin/product/insert', response: 'redirect' },
{ route: '/admin/product/edit/:id', response: 'redirect' },
{ route: '/admin/product/update', response: 'redirect' },
{ route: '/admin/product/delete/:id', response: 'redirect' },
{ route: '/admin/product/publishedState', response: 'json' },
{ route: '/admin/product/setasmainimage', response: 'json' },
{ route: '/admin/product/deleteimage', response: 'json' },
{ route: '/admin/product/removeoption', response: 'json' },
{ route: '/admin/order/updateorder', response: 'json' },
{ route: '/admin/settings/update', response: 'json' },
{ route: '/admin/settings/pages/new', response: 'redirect' },
{ route: '/admin/settings/pages/edit/:page', response: 'redirect' },
{ route: '/admin/settings/pages', response: 'json' },
{ route: '/admin/settings/page/delete/:page', response: 'json' },
{ route: '/admin/settings/menu/new', response: 'json' },
{ route: '/admin/settings/menu/update', response: 'json' },
{ route: '/admin/settings/menu/delete', response: 'json' },
{ route: '/admin/settings/menu/saveOrder', response: 'json' },
{ route: '/admin/file/upload', response: 'json' }
{ route: "/admin/product/new", response: "redirect" },
{ route: "/admin/product/insert", response: "redirect" },
{ route: "/admin/product/edit/:id", response: "redirect" },
{ route: "/admin/product/update", response: "redirect" },
{ route: "/admin/product/delete/:id", response: "redirect" },
{ route: "/admin/product/publishedState", response: "json" },
{ route: "/admin/product/setasmainimage", response: "json" },
{ route: "/admin/product/deleteimage", response: "json" },
{ route: "/admin/product/removeoption", response: "json" },
{ route: "/admin/order/updateorder", response: "json" },
{ route: "/admin/settings/update", response: "json" },
{ route: "/admin/settings/pages/new", response: "redirect" },
{ route: "/admin/settings/pages/edit/:page", response: "redirect" },
{ route: "/admin/settings/pages", response: "json" },
{ route: "/admin/settings/page/delete/:page", response: "json" },
{ route: "/admin/settings/menu/new", response: "json" },
{ route: "/admin/settings/menu/update", response: "json" },
{ route: "/admin/settings/menu/delete", response: "json" },
{ route: "/admin/settings/menu/saveOrder", response: "json" },
{ route: "/admin/file/upload", response: "json" },
];

const restrict = (req, res, next) => {
checkLogin(req, res, next);
checkLogin(req, res, next);
};

const checkLogin = async (req, res, next) => {
const db = req.app.db;
// if not protecting we check for public pages and don't checkLogin
if(req.session.needsSetup === true){
res.redirect('/admin/setup');
return;
}

// If API key, check for a user
if(req.headers.apikey){
try{
const user = await db.users.findOne({
apiKey: ObjectId(req.headers.apikey),
isAdmin: true
});
if(!user){
res.status(400).json({ message: 'Access denied' });
return;
}
// Set API authenticated in the req
req.apiAuthenticated = true;
next();
return;
}catch(ex){
res.status(400).json({ message: 'Access denied' });
return;
}
}
const db = req.app.db;
// if not protecting we check for public pages and don't checkLogin
if (req.session.needsSetup === true) {
res.redirect("/admin/setup");
return;
}

if(req.session.user){
next();
// If API key, check for a user
if (req.headers.apikey) {
try {
const user = await db.users.findOne({
apiKey: ObjectId(req.headers.apikey),
isAdmin: true,
});
if (!user) {
res.status(400).json({ message: "Access denied" });
return;
}
// Set API authenticated in the req
req.apiAuthenticated = true;
next();
return;
} catch (error) {
res.status(400).json({
status: "Failed",
message: "Access denied",
});
return;
}
res.redirect('/admin/login');
}

if (req.session.user) {
next();
return;
}
res.redirect("/admin/login");
};

// Middleware to check for admin access for certain route
const checkAccess = (req, res, next) => {
const routeCheck = _.find(restrictedRoutes, { route: req.route.path });
const routeCheck = lodash.find(restrictedRoutes, { route: req.route.path });

// If the user is not an admin and route is restricted, show message and redirect to /admin
if(req.session.isAdmin === false && routeCheck){
if(routeCheck.response === 'redirect'){
req.session.message = 'Unauthorised. Please refer to administrator.';
req.session.messageType = 'danger';
res.redirect('/admin');
return;
}
if(routeCheck.response === 'json'){
res.status(400).json({ message: 'Unauthorised. Please refer to administrator.' });
}
}else{
next();
// If the user is not an admin and route is restricted, show message and redirect to /admin
if (req.session.isAdmin === false && routeCheck) {
if (routeCheck.response === "redirect") {
req.session.message = "Unauthorised Please refer to administrator.";
req.session.messageType = "danger";
res.redirect("/admin");
return;
}
if (routeCheck.response === "json") {
res
.status(400)
.json({ message: "Unauthorised. Please refer to administrator." });
}
} else {
next();
}
};

module.exports = {
restrict,
checkLogin,
checkAccess
restrict,
checkLogin,
checkAccess,
};
208 changes: 105 additions & 103 deletions lib/cart.js
Original file line number Diff line number Diff line change
@@ -1,119 +1,121 @@
const {
getConfig
} = require('./config');
const { getConfig } = require("./config");

const updateTotalCart = async (req, res) => {
const config = getConfig();
const db = req.app.db;

req.session.totalCartAmount = 0;
req.session.totalCartItems = 0;
req.session.totalCartProducts = 0;

// If cart is empty return zero values
if(!req.session.cart){
return;
}

Object.keys(req.session.cart).forEach((item) => {
req.session.totalCartAmount = req.session.totalCartAmount + req.session.cart[item].totalItemPrice;
req.session.totalCartProducts = req.session.totalCartProducts + req.session.cart[item].quantity;
const config = getConfig();
const db = req.app.db;

req.session.totalCartAmount = 0;
req.session.totalCartItems = 0;
req.session.totalCartProducts = 0;

// If cart is empty return zero values
if (!req.session.cart) {
return;
}

Object.keys(req.session.cart).forEach((item) => {
req.session.totalCartAmount =
req.session.totalCartAmount + req.session.cart[item].totalItemPrice;
req.session.totalCartProducts =
req.session.totalCartProducts + req.session.cart[item].quantity;
});

// Update the total items in cart for the badge
req.session.totalCartItems = Object.keys(req.session.cart).length;

// Update the total amount not including shipping/discounts
req.session.totalCartNetAmount = req.session.totalCartAmount;

// Update checking cart for subscription
updateSubscriptionCheck(req, res);

// Calculate shipping using the loaded module
config.modules.loaded.shipping.calculateShipping(
req.session.totalCartNetAmount,
config,
req
);

// If discount module enabled
if (config.modules.loaded.discount) {
// Recalculate discounts
const discount = await db.discounts.findOne({
code: req.session.discountCode,
});

// Update the total items in cart for the badge
req.session.totalCartItems = Object.keys(req.session.cart).length;

// Update the total amount not including shipping/discounts
req.session.totalCartNetAmount = req.session.totalCartAmount;

// Update checking cart for subscription
updateSubscriptionCheck(req, res);

// Calculate shipping using the loaded module
config.modules.loaded.shipping.calculateShipping(
req.session.totalCartNetAmount,
config,
req
);

// If discount module enabled
if(config.modules.loaded.discount){
// Recalculate discounts
const discount = await db.discounts.findOne({ code: req.session.discountCode });
if(discount){
config.modules.loaded.discount.calculateDiscount(
discount,
req
);
}else{
// If discount code is not found, remove it
delete req.session.discountCode;
req.session.totalCartDiscount = 0;
}
if (discount) {
config.modules.loaded.discount.calculateDiscount(discount, req);
} else {
// If discount code is not found, remove it
delete req.session.discountCode;
req.session.totalCartDiscount = 0;
}
}

// Calculate our total amount removing discount and adding shipping
req.session.totalCartAmount = (req.session.totalCartNetAmount - req.session.totalCartDiscount) + req.session.totalCartShipping;
// Calculate our total amount removing discount and adding shipping
req.session.totalCartAmount =
req.session.totalCartNetAmount -
req.session.totalCartDiscount +
req.session.totalCartShipping;
};

const updateSubscriptionCheck = (req, res) => {
// If cart is empty
if(!req.session.cart || req.session.cart.length === 0){
req.session.cartSubscription = null;
return;
// If cart is empty
if (!req.session.cart || req.session.cart.length === 0) {
req.session.cartSubscription = null;
return;
}

Object.keys(req.session.cart).forEach((item) => {
if (req.session.cart[item].productSubscription) {
req.session.cartSubscription = req.session.cart[item].productSubscription;
} else {
req.session.cartSubscription = null;
}

Object.keys(req.session.cart).forEach((item) => {
if(req.session.cart[item].productSubscription){
req.session.cartSubscription = req.session.cart[item].productSubscription;
}else{
req.session.cartSubscription = null;
}
});
});
};

const emptyCart = async (req, res, type, customMessage) => {
const db = req.app.db;

// Remove from session
delete req.session.cart;
delete req.session.shippingAmount;
delete req.session.orderId;
delete req.session.cartSubscription;
delete req.session.discountCode;

// Remove cart from DB
await db.cart.deleteOne({ sessionId: req.session.id });

// update total cart
await updateTotalCart(req, res);

// Update checking cart for subscription
updateSubscriptionCheck(req, res);

// Set returned message
let message = 'Cart successfully emptied';
if(customMessage){
message = customMessage;
}

if(type === 'function'){
return;
}

// If POST, return JSON else redirect nome
if(type === 'json'){
res.status(200).json({ message: message, totalCartItems: 0 });
return;
}

req.session.message = message;
req.session.messageType = 'success';
res.redirect('/');
const db = req.app.db;

// Remove from session
delete req.session.cart;
delete req.session.shippingAmount;
delete req.session.orderId;
delete req.session.cartSubscription;
delete req.session.discountCode;

// Remove cart from DB
await db.cart.deleteOne({ sessionId: req.session.id });

// update total cart
await updateTotalCart(req, res);

// Update checking cart for subscription
updateSubscriptionCheck(req, res);

// Set returned message
let message = "Cart successfully emptied";
if (customMessage) {
message = customMessage;
}

if (type === "function") {
return;
}

// If POST, return JSON else redirect nome
if (type === "json") {
res.status(200).json({ message: message, totalCartItems: 0 });
return;
}

req.session.message = message;
req.session.messageType = "success";
res.redirect("/");
};

module.exports = {
updateTotalCart,
updateSubscriptionCheck,
emptyCart
updateTotalCart,
updateSubscriptionCheck,
emptyCart,
};
Loading