<commit_before>// We first require our express package
var express = require('express');
var bodyParser = require('body-parser');
var cartData = require('./data_cart.js');
var recipeData = require('./data_recipe.js');
var usersData = require('./data_users.js');
var cookieParser = require('cookie-parser');
var Guid = require('Guid');
var _xss = require('xss');
// This package exports the function to create an express instance:
var app = express();

// We can setup Jade now!
app.set('view engine', 'ejs');

// This is called 'adding middleware', or things that will help parse your request
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
app.use(cookieParser()); //for parsing cookies


app.use('/assets', express.static('static'));


app.use('/logout',function(request, response, next){
        var sessionID = request.cookies.currentSessionID;

        usersData.removeSessionId(sessionID);

        var anHourAgo = new Date();
        anHourAgo.setHours(anHourAgo.getHours() -1);

        response.cookie("currentSessionId", "", {expires : anHourAgo});
        response.clearCookie("currentSessionId");
		
		response.cookie("isAdmin", "", {expires : anHourAgo});
        response.clearCookie("isAdmin");
        next();
});


app.use('/add-product',function(request, response, next){
        if(request.cookies.isAdmin){
            next();
        }
        else
        {
            response.redirect("/");
        }
    
});

app.use(function(request, response, next) {


    if(request.cookies.currentSessionId)
            {
                usersData.getUserBySessionId(request.cookies.currentSessionId).then(function(result){


                    if(result.length == 1)
                    {

                        next();
                    }
                }).catch(function(error){
                    console.log(error)
                    var anHourAgo = new Date();
                    anHourAgo.setHours(anHourAgo.getHours() -1);

                    response.cookie("currentSessionId", "", {expires : anHourAgo});
                    response.clearCookie("currentSessionId");
					response.cookie("isAdmin", "", {expires : anHourAgo});
					response.clearCookie("isAdmin");
                    response.redirect("/");


                });
                return;

            }



    next();
});



// Setup your routes here!

app.get("/", function (request, response) {
    if(request.cookies.currentSessionId){
        usersData.getUserBySessionId(request.cookies.currentSessionId).then(function (user) {
            cartData.getCart(user[0].cartId).then(function (cart) {
                response.render("pages/homepage", {loginFlag: request.cookies.currentSessionId, adminFlag: request.cookies.isAdmin, pageTitle: "Home", cartCount: cart.recipes.length});
            }).catch(function(errorMessage){
                console.log(errorMessage);
            });
        }).catch(function(errorMessage){
            response.redirect("/login");
        });
    }
    else
    {
        response.render("pages/homepage", {loginFlag: request.cookies.currentSessionId, pageTitle: "Home"});
    }
});

app.post("/logout", function (request, response) {
    response.redirect("/");
});

app.get("/login",function (request, response){
    response.render("pages/index", {loginFlag: request.cookies.currentSessionId, pageTitle: "Login"});
});



// Create a user
app.post("/createUser", function(request, response) {
    usersData.createUser(_xss(request.body.register_email),_xss(request.body.register_passwd)).then(function(user) {
        console.log(user);
		
        if(user != "User already exists") {
            var expiresAt = new Date();
            expiresAt.setHours(expiresAt.getHours() + 1);
            response.cookie('currentSessionId', user.currentSessionId, { expires: expiresAt });
			
			if(_xss(request.body.register_email) == '<EMAIL>'){
				response.cookie('isAdmin', 'true', { expires: expiresAt });
			}
            response.redirect("/");
        }else {

            response.render("pages/index", {error: "User already exists. Try Logging in.", pageTitle: "Registration Error"});

        }
    }, function(errorMessage) {
        response.status(500).json({ error: errorMessage });
    });
});

// Login
app.post("/login", function(request, response) {
    var uname,pwd;
    uname = _xss(request.body.login_email);
    pwd = _xss(request.body.login_passwd);
    if(uname && pwd){
    usersData.validateUser(uname, pwd).then(function(newSessionId) {
        var expiresAt = new Date();
            expiresAt.setHours(expiresAt.getHours() + 1);
            response.cookie('currentSessionId', newSessionId, { expires: expiresAt });

        response.redirect("/");
    }, function(errorMessage) {
        response.render("pages/index", {error: errorMessage, pageTitle: "Login Error"});
    });
    }
});




app.get("/product/category/:category",function (request, response){
    var category = _xss(request.params.category);

    if(request.cookies.currentSessionId){
        usersData.getUserBySessionId(request.cookies.currentSessionId).then(function (user) {
            cartData.getCart(user[0].cartId).then(function (cart) {
                var category = _xss(request.params.category);
				if(category == 'Favorites'){
					usersData.getUserFavorites(user[0]._id).then(function(fave){
                        var favorites = [];
                        for (var f = 0; f < fave.length; f++) {
                            (function(f) {
                                recipeData.getRecipe(fave[f]).then(function(rec) {
                                    favorites.push(rec);
                                    if (f == fave.length-1) {
                                        response.render("pages/product_category", {resultData : favorites, category: category, loginFlag: request.cookies.currentSessionId, adminFlag: request.cookies.isAdmin, pageTitle: "Categories", cartCount: cart.recipes.length});
                                    }
                                });
                            })(f);
                        }
					});
						
                } else {
                    recipeData.getCategory(category).then(function(result){
                        for(var i=0; i<result.length; i++)
                        {
                            result[i] = recipeData.totalPrice(result[i]);
                        }
                        response.render("pages/product_category", {resultData : result, category: category, loginFlag: request.cookies.currentSessionId, adminFlag: request.cookies.isAdmin, pageTitle: "Categories", cartCount: cart.recipes.length})
                       });
				}

            }).catch(function(errorMessage){
                console.log(errorMessage);
            });
        }).catch(function(errorMessage){
            response.redirect("/login");
        });
    }
    else
    {
        var category = _xss(request.params.category);<commit_msg>final<commit_after>// We first require our express package
var express = require('express');
var bodyParser = require('body-parser');
var cartData = require('./data_cart.js');
var recipeData = require('./data_recipe.js');
var usersData = require('./data_users.js');
var cookieParser = require('cookie-parser');
var Guid = require('Guid');
var _xss = require('xss');
// This package exports the function to create an express instance:
var app = express();

// We can setup Jade now!
app.set('view engine', 'ejs');

// This is called 'adding middleware', or things that will help parse your request
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
app.use(cookieParser()); //for parsing cookies


app.use('/assets', express.static('static'));


app.use('/logout',function(request, response, next){
        var sessionID = request.cookies.currentSessionID;

        usersData.removeSessionId(sessionID);

        var anHourAgo = new Date();
        anHourAgo.setHours(anHourAgo.getHours() -1);

        response.cookie("currentSessionId", "", {expires : anHourAgo});
        response.clearCookie("currentSessionId");
		
		response.cookie("isAdmin", "", {expires : anHourAgo});
        response.clearCookie("isAdmin");
        next();
});


app.use('/add-product',function(request, response, next){
        if(request.cookies.isAdmin){
            next();
        }
        else
        {
            response.redirect("/");
        }
    
});

app.use(function(request, response, next) {


    if(request.cookies.currentSessionId)
            {
                usersData.getUserBySessionId(request.cookies.currentSessionId).then(function(result){


                    if(result.length == 1)
                    {

                        next();
                    }
                }).catch(function(error){
                    console.log(error)
                    var anHourAgo = new Date();
                    anHourAgo.setHours(anHourAgo.getHours() -1);

                    response.cookie("currentSessionId", "", {expires : anHourAgo});
                    response.clearCookie("currentSessionId");
					response.cookie("isAdmin", "", {expires : anHourAgo});
					response.clearCookie("isAdmin");
                    response.redirect("/");


                });
                return;

            }



    next();
});



// Setup your routes here!

app.get("/", function (request, response) {
    if(request.cookies.currentSessionId){
        usersData.getUserBySessionId(request.cookies.currentSessionId).then(function (user) {
            cartData.getCart(user[0].cartId).then(function (cart) {
                response.render("pages/homepage", {loginFlag: request.cookies.currentSessionId, adminFlag: request.cookies.isAdmin, pageTitle: "Home", cartCount: cart.recipes.length});
            }).catch(function(errorMessage){
                console.log(errorMessage);
            });
        }).catch(function(errorMessage){
            response.redirect("/login");
        });
    }
    else
    {
        response.render("pages/homepage", {loginFlag: request.cookies.currentSessionId, pageTitle: "Home"});
    }
});

app.post("/logout", function (request, response) {
    response.redirect("/");
});

app.get("/login",function (request, response){
    response.render("pages/index", {loginFlag: request.cookies.currentSessionId, pageTitle: "Login"});
});



// Create a user
app.post("/createUser", function(request, response) {
    usersData.createUser(_xss(request.body.register_email),_xss(request.body.register_passwd)).then(function(user) {
        console.log(user);
		
        if(user != "User already exists") {
            var expiresAt = new Date();
            expiresAt.setHours(expiresAt.getHours() + 1);
            response.cookie('currentSessionId', user.currentSessionId, { expires: expiresAt });
			
			if(_xss(request.body.register_email) == '<EMAIL>'){
				response.cookie('isAdmin', 'true', { expires: expiresAt });
			}
            response.redirect("/");
        }else {

            response.render("pages/index", {error: "User already exists. Try Logging in.", pageTitle: "Registration Error"});

        }
    }, function(errorMessage) {
        response.status(500).json({ error: errorMessage });
    });
});

// Login
app.post("/login", function(request, response) {
    var uname,pwd;
    uname = _xss(request.body.login_email);
    pwd = _xss(request.body.login_passwd);
    if(uname && pwd){
    usersData.validateUser(uname, pwd).then(function(newSessionId) {
        var expiresAt = new Date();
            expiresAt.setHours(expiresAt.getHours() + 1);
            response.cookie('currentSessionId', newSessionId, { expires: expiresAt });

        response.redirect("/");
    }, function(errorMessage) {
        response.render("pages/index", {error: errorMessage, pageTitle: "Login Error"});
    });
    }
});




app.get("/product/category/:category",function (request, response){
    var category = _xss(request.params.category);

    if(request.cookies.currentSessionId){
        usersData.getUserBySessionId(request.cookies.currentSessionId).then(function (user) {
            cartData.getCart(user[0].cartId).then(function (cart) {
                var category = _xss(request.params.category);
				if(category == 'Favorites'){
					usersData.getUserFavorites(user[0]._id).then(function(fave){
                         if (fave.length == 0) {
                             response.render("pages/product_category", {resultData : [], loginFlag: request.cookies.currentSessionId, adminFlag: request.cookies.isAdmin, pageTitle: "Categories", cartCount: cart.recipes.length});
                         } else {
                             var favorites = [];
                             for (var f = 0; f < fave.length; f++) {
                                 (function(f) {
                                     recipeData.getRecipe(fave[f]).then(function(rec) {
                                         favorites.push(rec);
                                         if (f == fave.length-1) {
                                             response.render("pages/product_category", {resultData : favorites, loginFlag: request.cookies.currentSessionId, adminFlag: request.cookies.isAdmin, pageTitle: "Categories", cartCount: cart.recipes.length});
                                         }
                                    });
                                 })(f);
                             }
                        }
					});
						
                } else {
                    recipeData.getCategory(category).then(function(result){
                        for(var i=0; i<result.length; i++)
                        {
                            result[i] = recipeData.totalPrice(result[i]);
                        }
                        response.render("pages/product_category", {resultData : result, category: category, loginFlag: request.cookies.currentSessionId, adminFlag: request.cookies.isAdmin, pageTitle: "Categories", cartCount: cart.recipes.length})
                       });
				}

            }).catch(function(errorMessage){
                console.log(errorMessage);
            });
        }).catch(function(errorMessage){
            response.redirect("/login");
        });
    }
    else
    {
        var category = _xss(request.params.category);
{'fraction_non_alphanumeric': 0.1415977961432507, 'fraction_numerical': 0.001997245179063361, 'mean_word_length': 2.187225636523266, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 17, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6086654', 'n_tokens_mistral': 4124, 'n_tokens_neox': 3868, 'n_words': 679}