<commit_before>'use strict';

module.exports = function (app, nconf, io) {
  var crypto = require('crypto');
  var Publico = require('meatspace-publico');
  var nativeClients = require('../clients.json');
  var blacklist = require('../blacklist.json');
  var level = require('level');

  var logger = level(nconf.get('logger'), {
    createIfMissing: true,
    valueEncoding: 'json'
  });

  var publico = new Publico('none', {
    db: './db',
    limit: 20
  });

  var blacklisted = function (fingerprint, userid) {
    if (blacklist.indexOf(fingerprint) > -1 || blacklist.indexOf(userid) > -1) {
      return true;
    }

    return false;
  };

  app.get('/info', function (req, res) {
    res.render('info');
  });

  app.get('/', function (req, res) {
    var currDate = Date.now();
    logger.put('landing-page!' + currDate, {
      ip: req.connection.remoteAddress,
      created: currDate
    });
    res.render('index');
  });

  app.get('/get/chats', function (req, res) {
    publico.getChats(false, function (err, c) {
      if (err) {
        res.status(400);
        res.json({ error: err.toString() });
      } else {
        res.json({ chats: c });

        io.sockets.on('connection', function (socket) {
          socket.on('recent', function (data) {
            if (nativeClients.indexOf(data.apiKey) > -1) {
              res.json({ chats: c });
            }
          });
        });
      }
    });
  });

  app.get('/ip', function (req, res) {
    res.json({
      ip: req.connection.remoteAddress
    });
  });

  var addChat = function (message, picture, fingerprint, userId, next) {
    if (!blacklisted(fingerprint, userId)) {
      publico.addChat(message.slice(0, 150), {
        ttl: 600000,
        media: picture,
        fingerprint: userId
      }, function (err, c) {
        if (err) {
          next(err);
        } else {
          try {
            io.sockets.emit('message', {
              chat: {
                key: c.key,
                value: {
                  fingerprint: userId,
                  created: c.created,
                  media: c.media,
                  ttl: c.ttl,
                  message: c.message
                }
              }
            });

            next(null, 'sent!');
          } catch (err) {
            next(new Error('Could not emit message'));
          }
        }
      });
    } else {
      next(new Error('access denied'));
    }
  };

  app.post('/add/chat', function (req, res, next) {
    var userId = crypto.createHash('md5').update(req.body.fingerprint + req.connection.remoteAddress).digest('hex');

    if (blacklisted()) {
      var currDate = Date.now();
      logger.put('blacklisted!' + currDate, {
        ip: req.connection.remoteAddress,
        fingerprint: userId,
        created: currDate
      });

      res.status(403);
      res.json({ error: 'access denied' });
    } else {
      if (req.body.picture) {
        if (userId && userId === req.body.userid) {
          addChat(req.body.message, req.body.picture, req.body.fingerprint, userId, function (err, status) {
            if (err) {
              res.status(400);
              res.json({ error: err.toString() });
            } else {
              var currDate = Date.now();
              logger.put('web!' + currDate, {
                ip: req.connection.remoteAddress,
                fingerprint: userId,
                created: currDate
              });

              res.json({ status: status });
            }
          });
        } else {
          res.status(403);
          res.json({ error: 'invalid fingerprint' });
        }
      } else {
        res.status(400);
        res.json({ error: 'you need webrtc' });
      }
    }
  });

  io.sockets.on('connection', function (socket) {
    socket.on('message', function (data) {
      if (nativeClients.indexOf(data.apiKey) > -1) {

        addChat(data.message, data.picture, data.fingerprint, data.fingerprint, function (err) {
          if (err) {
            console.log('error posting ', err.toString());
          } else {
            var currDate = Date.now();
            logger.put('api!' + currDate, {
              ip: '0.0.0.0',
              fingerprint: data.fingerprint,
              created: currDate
            });
          }
        });
      } else {
        console.log('Invalid apiKey: ', data.apiKey);
      }
    });
  });
};
<commit_msg>switch order of messages<commit_after>'use strict';

module.exports = function (app, nconf, io) {
  var crypto = require('crypto');
  var Publico = require('meatspace-publico');
  var nativeClients = require('../clients.json');
  var blacklist = require('../blacklist.json');
  var level = require('level');

  var logger = level(nconf.get('logger'), {
    createIfMissing: true,
    valueEncoding: 'json'
  });

  var publico = new Publico('none', {
    db: './db',
    limit: 20
  });

  var blacklisted = function (fingerprint, userid) {
    if (blacklist.indexOf(fingerprint) > -1 || blacklist.indexOf(userid) > -1) {
      return true;
    }

    return false;
  };

  app.get('/info', function (req, res) {
    res.render('info');
  });

  app.get('/', function (req, res) {
    var currDate = Date.now();
    logger.put('landing-page!' + currDate, {
      ip: req.connection.remoteAddress,
      created: currDate
    });
    res.render('index');
  });

  app.get('/get/chats', function (req, res) {
    publico.getChats(true, function (err, c) {
      if (err) {
        res.status(400);
        res.json({ error: err.toString() });
      } else {
        res.json({ chats: c });

        io.sockets.on('connection', function (socket) {
          socket.on('recent', function (data) {
            if (nativeClients.indexOf(data.apiKey) > -1) {
              res.json({ chats: c });
            }
          });
        });
      }
    });
  });

  app.get('/ip', function (req, res) {
    res.json({
      ip: req.connection.remoteAddress
    });
  });

  var addChat = function (message, picture, fingerprint, userId, next) {
    if (!blacklisted(fingerprint, userId)) {
      publico.addChat(message.slice(0, 150), {
        ttl: 600000,
        media: picture,
        fingerprint: userId
      }, function (err, c) {
        if (err) {
          next(err);
        } else {
          try {
            io.sockets.emit('message', {
              chat: {
                key: c.key,
                value: {
                  fingerprint: userId,
                  created: c.created,
                  media: c.media,
                  ttl: c.ttl,
                  message: c.message
                }
              }
            });

            next(null, 'sent!');
          } catch (err) {
            next(new Error('Could not emit message'));
          }
        }
      });
    } else {
      next(new Error('access denied'));
    }
  };

  app.post('/add/chat', function (req, res, next) {
    var userId = crypto.createHash('md5').update(req.body.fingerprint + req.connection.remoteAddress).digest('hex');

    if (blacklisted()) {
      var currDate = Date.now();
      logger.put('blacklisted!' + currDate, {
        ip: req.connection.remoteAddress,
        fingerprint: userId,
        created: currDate
      });

      res.status(403);
      res.json({ error: 'access denied' });
    } else {
      if (req.body.picture) {
        if (userId && userId === req.body.userid) {
          addChat(req.body.message, req.body.picture, req.body.fingerprint, userId, function (err, status) {
            if (err) {
              res.status(400);
              res.json({ error: err.toString() });
            } else {
              var currDate = Date.now();
              logger.put('web!' + currDate, {
                ip: req.connection.remoteAddress,
                fingerprint: userId,
                created: currDate
              });

              res.json({ status: status });
            }
          });
        } else {
          res.status(403);
          res.json({ error: 'invalid fingerprint' });
        }
      } else {
        res.status(400);
        res.json({ error: 'you need webrtc' });
      }
    }
  });

  io.sockets.on('connection', function (socket) {
    socket.on('message', function (data) {
      if (nativeClients.indexOf(data.apiKey) > -1) {

        addChat(data.message, data.picture, data.fingerprint, data.fingerprint, function (err) {
          if (err) {
            console.log('error posting ', err.toString());
          } else {
            var currDate = Date.now();
            logger.put('api!' + currDate, {
              ip: '0.0.0.0',
              fingerprint: data.fingerprint,
              created: currDate
            });
          }
        });
      } else {
        console.log('Invalid apiKey: ', data.apiKey);
      }
    });
  });
};
<|endoftext|>


<commit_before>var express = require('express');
var router = express.Router();

db = require('../queries');

router.get('/api/todos', db.getAllTodos);
router.get('/api/todos/:id', db.getTodo);
router.post('/api/todos', db.addTodo);
router.put('/api/todos/:id', db.updateTodo);
router.delete('/api/todos/:id', db.removeTodo);

module.exports = router;
<commit_msg>Add static method in order to serve pages on /public<commit_after>var express = require('express');
var router = express.Router();

db = require('../queries');

router.use(express.static('public'));
router.get('/api/todos', db.getAllTodos);
router.get('/api/todos/:id', db.getTodo);
router.post('/api/todos', db.addTodo);
router.put('/api/todos/:id', db.updateTodo);
router.delete('/api/todos/:id', db.removeTodo);

module.exports = router;
<|endoftext|>


<commit_before>var db = require('../db'),
	util = require('../util'),
	async = require('async'),
	crypto = require('crypto')
/*
 * GET home page.
 */

var self = exports;

exports.index = function(req, res) {
	async.series({
		quotes: function(callback) {
			db.query("SELECT c.`text` as `text`,u.username as username FROM quotes c LEFT JOIN users u ON u.id=c.uid", [], callback);
		},
		clubs: function(callback) {
			db.query("SELECT * FROM clubs ORDER BY `order` DESC", [], callback);
		}
	}, function(err, results) {
		if (err) return util.error(err, req, res, "Couldn't render index page, try again later.");

		res.render('index', {title:'It burns when I pee.', clubs:results.clubs, randomquote:util.randomElement(results.quotes)});
	});
};

exports.fund = function(req, res) {
	db.query("SELECT * FROM fund", [], function(err, results) {
		if (err) return util.error(err, req, res, "Couldn't get church fund balance sheet.");

		db.query("SELECT * FROM fund_btcusd", [], function(err, btcusd_results) {
			if (err) return util.error(err, req, res, "Couldn't get historic BTCUSD rate.");

			var btcusd = {};
			btcusd_results.forEach(function(day) {
				btcusd[Math.floor(day.date / 86400) * 86400] = day.btcusd;
			})

			res.render('fund', {title:'Fund', fund:results, btcusd:btcusd});
		})
	})
};

exports.mail = function(req, res) {
	if (res.locals.__AUTH_LOGGED_IN) {
		if (res.locals.__AUTH_USERDATA['webmail']) {
			var sha1 = crypto.createHash('sha1');
			var t = util.timeNow();
			sha1.update(process.env.DBPASS + ":" + res.locals.__AUTH_USERDATA['webmail'] + ":" + t);
			var hmac = sha1.digest('hex');

			util.redirect(req, res, "https://mail.quibs.org/?u=" + res.locals.__AUTH_USERDATA['webmail'] + "&hmac=" + hmac + "&t=" + t, true);
			//res.send("https://mail.quibs.org/?u=" + res.locals.__AUTH_USERDATA['webmail'] + "&hmac=" + hmac + "&t=" + t);
		} else {
			res.send("you don't have a webmail");
		}
	} else {
		res.send("you're not logged in");
	}
}

exports.quotes = require('./quotes')
exports.grants = require('./grants')
exports.blog = require('./blog') // todo: might as well merge this with blogpost anyway
exports.blogpost = require('./blogpost')
exports.comments = require('./comments')
exports.gallery = require('./gallery')
exports.user = require('./user')
exports.notifications = require('./notifications')
exports.clubs = require('./clubs')
<commit_msg>Redirect for mail purposes (closes #36).<commit_after>var db = require('../db'),
	util = require('../util'),
	async = require('async'),
	crypto = require('crypto')
/*
 * GET home page.
 */

var self = exports;

exports.index = function(req, res) {
	async.series({
		quotes: function(callback) {
			db.query("SELECT c.`text` as `text`,u.username as username FROM quotes c LEFT JOIN users u ON u.id=c.uid", [], callback);
		},
		clubs: function(callback) {
			db.query("SELECT * FROM clubs ORDER BY `order` DESC", [], callback);
		}
	}, function(err, results) {
		if (err) return util.error(err, req, res, "Couldn't render index page, try again later.");

		res.render('index', {title:'It burns when I pee.', clubs:results.clubs, randomquote:util.randomElement(results.quotes)});
	});
};

exports.fund = function(req, res) {
	db.query("SELECT * FROM fund", [], function(err, results) {
		if (err) return util.error(err, req, res, "Couldn't get church fund balance sheet.");

		db.query("SELECT * FROM fund_btcusd", [], function(err, btcusd_results) {
			if (err) return util.error(err, req, res, "Couldn't get historic BTCUSD rate.");

			var btcusd = {};
			btcusd_results.forEach(function(day) {
				btcusd[Math.floor(day.date / 86400) * 86400] = day.btcusd;
			})

			res.render('fund', {title:'Fund', fund:results, btcusd:btcusd});
		})
	})
};

exports.mail = function(req, res) {
	if (res.locals.__AUTH_LOGGED_IN) {
		if (res.locals.__AUTH_USERDATA['webmail']) {
			var sha1 = crypto.createHash('sha1');
			var t = util.timeNow();
			sha1.update(process.env.DBPASS + ":" + res.locals.__AUTH_USERDATA['webmail'] + ":" + t);
			var hmac = sha1.digest('hex');

			util.redirect(req, res, "https://mail.quibs.org/?u=" + res.locals.__AUTH_USERDATA['webmail'] + "&hmac=" + hmac + "&t=" + t, true);
		} else {
			res.locals.msg = "Ask quibs for an email account.";
			util.redirect(req, res, "/");
		}
	} else {
		res.locals.msg = "You must be logged in to use the webmail.";
		util.redirect(req, res, "/login");
	}
}

exports.quotes = require('./quotes')
exports.grants = require('./grants')
exports.blog = require('./blog') // todo: might as well merge this with blogpost anyway
exports.blogpost = require('./blogpost')
exports.comments = require('./comments')
exports.gallery = require('./gallery')
exports.user = require('./user')
exports.notifications = require('./notifications')
exports.clubs = require('./clubs')
<|endoftext|>


<commit_before>var _ = require('underscore'),
	keystone = require('keystone'),
	importRoutes = keystone.importer(__dirname);

function restrictToAdmins(req, res, next) {
	if (req.user && req.user.isAdmin) {
		next();
	} else {
		res.redirect('/signin');
	}
}

keystone.pre('routes', function(req, res, next) {

	res.locals.navLinks = [
		{ label: 'Home', key: 'home', href: '/' },
		{ label: 'Company info', key: 'company', href: '/#' },
		{ label: 'Offering', key: 'offering', href: '/offering' },
		{ label: 'Contact Us', key: 'contact', href: '/#' },
		//{ label: 'Sign In', key: 'signin', href: '/keystone/signin' }
	];

	res.locals.user = req.user;

	next();

});

keystone.pre('render', function(req, res, next) {

	var flashMessages = {
		info: req.flash('info'),
		success: req.flash('success'),
		warning: req.flash('warning'),
		error: req.flash('error')
	};

	res.locals.messages = _.any(flashMessages, function(msgs) { return msgs.length }) ? flashMessages : false;

	next();

});

keystone.set('404', function(req, res, next) {
	res.status(404).render('errors/404');
});

// Load Routes
var routes = {
	//api: importRoutes('./api'),
	download: importRoutes('./download'),
	views: importRoutes('./views')
};

exports = module.exports = function(app) {

	// Views
	app.get('/', routes.views.index);
	// app.get('/blog/:category?', routes.views.blog);
	// app.all('/blog/post/:post', routes.views.post);
	// app.get('/gallery', routes.views.gallery);
	// app.all('/contact', routes.views.contact);
	app.all('/companyprofile', routes.views.companyprofile);
	app.get('/companyinfolistmenu',routes.views.companyinfolistmenu);
	app.all('/mangementteam', routes.views.mangementteam);
	app.all('/differentiator', routes.views.differentiator);
	app.all('/career', routes.views.career);
	app.all('/partner', routes.views.partner);
	app.get('/softwareproduct', routes.views.softwareproduct);
	app.get('/listingmenu',routes.views.listingmenu);
	app.get('/consultingservice', routes.views.consultingservice);
	app.get('/msp',routes.views.msp);
	app.get('/specializedanalyse',routes.views.specializedanalyse);
	app.all('/offering', routes.views.offering);
	app.all('/technologyresale', routes.views.technologyresale);
	app.all('/contactform', routes.views.contactform);
	app.all('/analyticalportal', routes.views.analyticalportal);
	app.all('/tibcospotfire', routes.views.tibcospotfire);
	app.all('/marketresearch', routes.views.marketresearch);
	app.all('/tibcospotfirecustom', routes.views.tibcospotfirecustom);
	app.all('/readmore', routes.views.readmore);

	// Downloads
	app.get('/download/users', routes.download.users);

	// API
	//app.all('/api*', keystone.initAPI);

}
<commit_msg>added data<commit_after>var _ = require('underscore'),
	keystone = require('keystone'),
	importRoutes = keystone.importer(__dirname);

function restrictToAdmins(req, res, next) {
	if (req.user && req.user.isAdmin) {
		next();
	} else {
		res.redirect('/signin');
	}
}

keystone.pre('routes', function(req, res, next) {

	res.locals.navLinks = [
		{ label: 'Home', key: 'home', href: '/' },
		{ label: 'Company info', key: 'company', href: '/#' },
		{ label: 'Offering', key: 'offering', href: '/offering' },
		{ label: 'Contact Us', key: 'contact', href: '/#' },
		//{ label: 'Sign In', key: 'signin', href: '/keystone/signin' }
	];

	res.locals.user = req.user;

	next();

});

keystone.pre('render', function(req, res, next) {

	var flashMessages = {
		info: req.flash('info'),
		success: req.flash('success'),
		warning: req.flash('warning'),
		error: req.flash('error')
	};

	res.locals.messages = _.any(flashMessages, function(msgs) { return msgs.length }) ? flashMessages : false;

	next();

});

keystone.set('404', function(req, res, next) {
	res.status(404).render('errors/404');
});

// Load Routes
var routes = {
	//api: importRoutes('./api'),
	download: importRoutes('./download'),
	views: importRoutes('./views')
};

exports = module.exports = function(app) {

	// Views
	app.get('/', routes.views.index);
	// app.get('/blog/:category?', routes.views.blog);
	// app.all('/blog/post/:post', routes.views.post);
	// app.get('/gallery', routes.views.gallery);
	// app.all('/contact', routes.views.contact);
	app.all('/companyprofile', routes.views.companyprofile);
	app.get('/companyinfolistmenu',routes.views.companyinfolistmenu);
	app.all('/mangementteam', routes.views.mangementteam);
	app.all('/differentiator', routes.views.differentiator);
	app.all('/career', routes.views.career);
	app.all('/partner', routes.views.partner);
	app.get('/softwareproduct', routes.views.softwareproduct);
	app.get('/listingmenu',routes.views.listingmenu);
	app.get('/consultingservice', routes.views.consultingservice);
	app.get('/msp',routes.views.msp);
	app.get('/specializedanalyse',routes.views.specializedanalyse);
	app.all('/offering', routes.views.offering);
	app.all('/technologyresale', routes.views.technologyresale);
	app.all('/contactform', routes.views.contactform);
	app.all('/analyticalportal', routes.views.analyticalportal);
	app.all('/tibcospotfire', routes.views.tibcospotfire);
	app.all('/marketresearch', routes.views.marketresearch);
	app.all('/tibcospotfirecustom', routes.views.tibcospotfirecustom);
	app.all('/readmore', routes.views.readmore);
	app.all('/errors/404', routes.views.errors);

	// Downloads
	app.get('/download/users', routes.download.users);

	// API
	//app.all('/api*', keystone.initAPI);

}
<|endoftext|>


<commit_before>
exports.index = function(req, res){
	var room = req.params.room;
	if(room !== 'r0' && room !== 'r1' && room !== 'r2') {
		res.status(404);

		if (req.accepts('html')) {
			res.render('404', { url: req.url });
			return;
		}
	}

	console.log("get : " + room);
	res.render('index', {'room': room});

};

<commit_msg>remove unused stuff<commit_after>

exports.index = function(req, res){
	var room = req.params.room;
	if(room !== 'r0' && room !== 'r1' && room !== 'r2') {
		res.status(404);

		if (req.accepts('html')) {
			res.render('404', { url: req.url });
			return;
		}
	}

	console.log("get : " + room);

	res.render('index', {room: room});

};

<|endoftext|>


<commit_before>var express = require('express');
var passport = require('passport');
var mongoose = require('mongoose');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
  res.sendFile(__dirname + '/client_views/index.html');
});

// Login and Registration
var User = mongoose.model('User');

router.post('/register', function(req, res, next){
	if(!req.body.email || !req.body.password
		|| !req.body.firstname || !req.body.lastname
		|| !req.body.origincountry || !req.body.origincity
		|| !req.body.destinationcountry|| !req.body.destinationcity
		|| !req.body.agree)
	{
		return res.status(400).json({message: 'Please fill out all fields.'});
	}

  // Anyone with the same e-mail?
  User.findOne({email: req.body.email}).exec(function (err, user){
        if (err) {
			return next(err);
		}

        if (user) {
			return res.status(400).json({message: 'A user with the same e-mail already exists.'});
		}

		var user = new User();

		user.email = req.body.email;
		user.firstname = req.body.firstname;
		user.lastname = req.body.lastname;
		user.origincountry = req.body.origincountry;
		user.origincity = req.body.origincity;
		user.destinationcountry = req.body.destinationcountry;
		user.destinationcity = req.body.destinationcity;
		user.age = req.body.age;

		user.setPassword(req.body.password)

		user.save(function (err){
			if(err){ return next(err); }

			return res.json({token: user.generateJWT()})
		});
	});
});

router.post('/login', function(req, res, next){
  if(!req.body.email || !req.body.password){
    return res.status(400).json({message: 'Please fill out all fields'});
  }

  passport.authenticate('local', function(err, user, info){
    if(err){ return next(err); }

    if(user){
      return res.json({token: user.generateJWT()});
    } else {
      return res.status(401).json(info);
    }
  })(req, res, next);
});

// route for facebook authentication and login
// different scopes while logging in
router.get('/login/facebook',
	passport.authenticate('facebook', { scope : 'email' }
));

// handle the callback after facebook has authenticated the user
router.get('/login/facebook/callback',
	passport.authenticate('facebook', {
		failureRedirect : '/'
	}),
	function(req, res, done) {

		User.findOne({ '_id': req.user._id }, function (err, doc){

			var jwt = doc.generateJWT();

			res.redirect('/#/facebook/' + jwt);
		});
});

// route for google authentication and login
// different scopes while logging in
router.get('/login/google',
	passport.authenticate('google', { scope : 'email' }
	));

// handle the callback after google has authenticated the user
router.get('/login/google/callback',
	passport.authenticate('google', {
		failureRedirect : '/'
	}),
	function(req, res, done) {

		User.findOne({ '_id': req.user._id }, function (err, doc){

			var jwt = doc.generateJWT();

			res.redirect('/#/google/' + jwt);
		});
	});

module.exports = router;
<commit_msg>Fix profile picture bug<commit_after>var express = require('express');
var passport = require('passport');
var mongoose = require('mongoose');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
  res.sendFile(__dirname + '/client_views/index.html');
});

// Login and Registration
var User = mongoose.model('User');

router.post('/register', function(req, res, next){
	if(!req.body.email || !req.body.password
		|| !req.body.firstname || !req.body.lastname
		|| !req.body.origincountry || !req.body.origincity
		|| !req.body.destinationcountry|| !req.body.destinationcity
		|| !req.body.agree)
	{
		return res.status(400).json({message: 'Please fill out all fields.'});
	}

  // Anyone with the same e-mail?
  User.findOne({email: req.body.email}).exec(function (err, user){
        if (err) {
			return next(err);
		}

        if (user) {
			return res.status(400).json({message: 'A user with the same e-mail already exists.'});
		}

		var user = new User();

		user.email = req.body.email;
		user.firstname = req.body.firstname;
		user.lastname = req.body.lastname;
		user.origincountry = req.body.origincountry;
		user.origincity = req.body.origincity;
		user.destinationcountry = req.body.destinationcountry;
		user.destinationcity = req.body.destinationcity;
		user.age = req.body.age;
		user.picture = '';

		user.setPassword(req.body.password)

		user.save(function (err){
			if(err){ return next(err); }

			return res.json({token: user.generateJWT()})
		});
	});
});

router.post('/login', function(req, res, next){
  if(!req.body.email || !req.body.password){
    return res.status(400).json({message: 'Please fill out all fields'});
  }

  passport.authenticate('local', function(err, user, info){
    if(err){ return next(err); }

    if(user){
      return res.json({token: user.generateJWT()});
    } else {
      return res.status(401).json(info);
    }
  })(req, res, next);
});

// route for facebook authentication and login
// different scopes while logging in
router.get('/login/facebook',
	passport.authenticate('facebook', { scope : 'email' }
));

// handle the callback after facebook has authenticated the user
router.get('/login/facebook/callback',
	passport.authenticate('facebook', {
		failureRedirect : '/'
	}),
	function(req, res, done) {

		User.findOne({ '_id': req.user._id }, function (err, doc){

			var jwt = doc.generateJWT();

			res.redirect('/#/facebook/' + jwt);
		});
});

// route for google authentication and login
// different scopes while logging in
router.get('/login/google',
	passport.authenticate('google', { scope : 'email' }
	));

// handle the callback after google has authenticated the user
router.get('/login/google/callback',
	passport.authenticate('google', {
		failureRedirect : '/'
	}),
	function(req, res, done) {

		User.findOne({ '_id': req.user._id }, function (err, doc){

			var jwt = doc.generateJWT();

			res.redirect('/#/google/' + jwt);
		});
	});

module.exports = router;
<|endoftext|>


<commit_before>/*eslint-env node */
var http = require('http');
var db = require('./db');
db.initDB();
var USE_FASTCACHE = false;

/*
 * To enable the load generator and 'improved' cache mechanism below:
 * 1. remove the 'res.json({"success": 0, "fail": 0, "time": 0});' line
 * 2. uncomment the remaining method body
 */
exports.loadTest = function(req, res) {
//    res.json({"success": 0, "fail": 0, "time": 0});
///*
    USE_FASTCACHE = true;
    var testCount = req.query.count;
    testCount = testCount ? parseInt(testCount) : 100;

    var successCount = 0, failCount = 0;
    var startTime = Date.now();

    var callback = function(response) {
        if (response.statusCode === 200) {
            successCount++;
        } else {
            failCount++;
        }

        if (successCount + failCount === testCount) {
            var endTime = Date.now();
            res.json({"success": successCount, "fail": failCount, "time": endTime - startTime});
        }
    };

    var itemId1 = "1f9e7891bffb03605e3a9b43f996f6ea";
    var itemId2 = "9dce21273d13dc1dcb1b47370359e753";
    for (var i = 0; i < testCount; i++) {
        http.get({
            host: req.get('host'),
            path: "/items/" + (i % 2 ? itemId1 : itemId2)
	}, callback);
    }
//*/
};

//Create and populate or delete the database.
exports.dbOptions = function(req, res) {
    var option = req.params.option.toLowerCase();
    if (option === 'create') {
        db.cloudant.db.create('items', function(err/*, body*/) {
            if (!err) {
                db.populateDB();
                res.send({msg:'Successfully created database and populated!'});
            } else {
                res.send({msg:err});
            }
        });
    } else if (option === 'delete') {
        db.cloudant.db.destroy('items', function(err/*, body*/) {
	        if (!err) {
	            res.send({msg:'Successfully deleted db items!'});
	        } else {
	        	res.send({msg:'Error deleting db items: ' + err});
        	}
        });
    } else {
    	res.send({msg: 'your option was not understood. Please use "create" or "delete"'});
	}
};

//Create an item to add to the database.
exports.create = function(req, res) {
    db.itemsDb.insert(req.body, function(err/*, body, headers*/) {
        if (!err) {
            res.send({msg: 'Successfully created item'});
        } else {
            res.send({msg: 'Error on insert, maybe the item already exists: ' + err});
        }
    });
};

//find an item by ID.
exports.find = function(req, res) {
    var id = req.params.id;
    if (USE_FASTCACHE) {
    	var idAsNumber = parseInt(id.substring(id.length - 2), 16);
    	if (!idAsNumber || idAsNumber % 3 === 2) {
        	res.status(500).send({msg: 'server error'});
    	} else {
    		res.status(200).send({msg: 'all good'});
    	}
        return;
    }
    db.itemsDb.get(id, { revs_info: false }, function(err, body) {
        if (!err) {
            res.send(body);
        } else {
            res.send({msg:'Error: could not find item: ' + id});
        }
    });
};

//list all the database contents.
exports.list = function(req, res) {
    db.itemsDb.list({include_docs: true}, function(err, body/*, headers*/) {
	    if (!err) {
	        res.send(body);
	        return;
	    }
	   	res.send({msg:'Error listing items: ' + err});
    });
};

//update an item using an ID.
exports.update = function(req, res) {
    var id = req.params.id;
    var data = req.body;
    db.itemsDb.get(id, {revs_info:true}, function(err, body) {
        if (!err) {
            data._rev = body._rev;
            db.itemsDb.insert(data, id, function(err/*, body, headers*/) {
	            if (!err) {
	                res.send({msg:'Successfully updated item: ' + JSON.stringify(data)});
	            } else {
	            	res.send({msg:'Error inserting for update: ' + err});
	        	}
            });
        }
        else {
        	res.send({msg:'Error getting item for update: ' + err});
    	}
    });
};

//remove an item from the database using an ID.
exports.remove =  function(req, res) {
    var id = req.params.id;
    db.itemsDb.get(id, { revs_info: true }, function(err, body) {
        if (!err) {
            //console.log('Deleting item: ' + id);
            db.itemsDb.destroy(id, body._rev, function(err/*, body*/) {
                if (!err) {
                    res.send({msg:'Successfully deleted item'});
                } else {
                    res.send({msg:'Error in delete: ' + err});
                }
            });
        } else {
            res.send({msg:'Error getting item id: ' + err});
        }
    });
};

//calculate the fibonacci of 20.
var fib = function(n) {
    if (n < 2) {
        return 1;
    }
    return fib(n - 2) + fib(n - 1);
};
exports.fib = function(req, res) {
    res.send({msg:'Done with fibonacci of 20: ' + fib(20)});
};

exports.getFastCache = function() {
    return USE_FASTCACHE;
};
<commit_msg>Revert "fixes hmagph/ui-feb17-10-onlinestore#1"<commit_after>/*eslint-env node */
var http = require('http');
var db = require('./db');
db.initDB();
var USE_FASTCACHE = false;

/*
 * To enable the load generator and 'improved' cache mechanism below:
 * 1. remove the 'res.json({"success": 0, "fail": 0, "time": 0});' line
 * 2. uncomment the remaining method body
 */
exports.loadTest = function(req, res) {
    res.json({"success": 0, "fail": 0, "time": 0});
/*
    USE_FASTCACHE = true;
    var testCount = req.query.count;
    testCount = testCount ? parseInt(testCount) : 100;

    var successCount = 0, failCount = 0;
    var startTime = Date.now();

    var callback = function(response) {
        if (response.statusCode === 200) {
            successCount++;
        } else {
            failCount++;
        }

        if (successCount + failCount === testCount) {
            var endTime = Date.now();
            res.json({"success": successCount, "fail": failCount, "time": endTime - startTime});
        }
    };

    var itemId1 = "1f9e7891bffb03605e3a9b43f996f6ea";
    var itemId2 = "9dce21273d13dc1dcb1b47370359e753";
    for (var i = 0; i < testCount; i++) {
        http.get({
            host: req.get('host'),
            path: "/items/" + (i % 2 ? itemId1 : itemId2)
	}, callback);
    }
*/
};

//Create and populate or delete the database.
exports.dbOptions = function(req, res) {
    var option = req.params.option.toLowerCase();
    if (option === 'create') {
        db.cloudant.db.create('items', function(err/*, body*/) {
            if (!err) {
                db.populateDB();
                res.send({msg:'Successfully created database and populated!'});
            } else {
                res.send({msg:err});
            }
        });
    } else if (option === 'delete') {
        db.cloudant.db.destroy('items', function(err/*, body*/) {
	        if (!err) {
	            res.send({msg:'Successfully deleted db items!'});
	        } else {
	        	res.send({msg:'Error deleting db items: ' + err});
        	}
        });
    } else {
    	res.send({msg: 'your option was not understood. Please use "create" or "delete"'});
	}
};

//Create an item to add to the database.
exports.create = function(req, res) {
    db.itemsDb.insert(req.body, function(err/*, body, headers*/) {
        if (!err) {
            res.send({msg: 'Successfully created item'});
        } else {
            res.send({msg: 'Error on insert, maybe the item already exists: ' + err});
        }
    });
};

//find an item by ID.
exports.find = function(req, res) {
    var id = req.params.id;
    if (USE_FASTCACHE) {
    	var idAsNumber = parseInt(id.substring(id.length - 2), 16);
    	if (!idAsNumber || idAsNumber % 3 === 2) {
        	res.status(500).send({msg: 'server error'});
    	} else {
    		res.status(200).send({msg: 'all good'});
    	}
        return;
    }
    db.itemsDb.get(id, { revs_info: false }, function(err, body) {
        if (!err) {
            res.send(body);
        } else {
            res.send({msg:'Error: could not find item: ' + id});
        }
    });
};

//list all the database contents.
exports.list = function(req, res) {
    db.itemsDb.list({include_docs: true}, function(err, body/*, headers*/) {
	    if (!err) {
	        res.send(body);
	        return;
	    }
	   	res.send({msg:'Error listing items: ' + err});
    });
};

//update an item using an ID.
exports.update = function(req, res) {
    var id = req.params.id;
    var data = req.body;
    db.itemsDb.get(id, {revs_info:true}, function(err, body) {
        if (!err) {
            data._rev = body._rev;
            db.itemsDb.insert(data, id, function(err/*, body, headers*/) {
	            if (!err) {
	                res.send({msg:'Successfully updated item: ' + JSON.stringify(data)});
	            } else {
	            	res.send({msg:'Error inserting for update: ' + err});
	        	}
            });
        }
        else {
        	res.send({msg:'Error getting item for update: ' + err});
    	}
    });
};

//remove an item from the database using an ID.
exports.remove =  function(req, res) {
    var id = req.params.id;
    db.itemsDb.get(id, { revs_info: true }, function(err, body) {
        if (!err) {
            //console.log('Deleting item: ' + id);
            db.itemsDb.destroy(id, body._rev, function(err/*, body*/) {
                if (!err) {
                    res.send({msg:'Successfully deleted item'});
                } else {
                    res.send({msg:'Error in delete: ' + err});
                }
            });
        } else {
            res.send({msg:'Error getting item id: ' + err});
        }
    });
};

//calculate the fibonacci of 20.
var fib = function(n) {
    if (n < 2) {
        return 1;
    }
    return fib(n - 2) + fib(n - 1);
};
exports.fib = function(req, res) {
    res.send({msg:'Done with fibonacci of 20: ' + fib(20)});
};

exports.getFastCache = function() {
    return USE_FASTCACHE;
};
<|endoftext|>


<commit_before>/*eslint-env node */
var http = require('http');
var db = require('./db');
db.initDB();
var USE_FASTCACHE = false;

/*
 * To enable the load generator and 'improved' cache mechanism below:
 * 1. remove the 'res.json({"success": 0, "fail": 0, "time": 0});' line
 * 2. uncomment the remaining method body
 */
exports.loadTest = function(req, res) {
    res.json({"success": 0, "fail": 0, "time": 0});
/*
    USE_FASTCACHE = true;
    var testCount = req.query.count;
    testCount = testCount ? parseInt(testCount) : 100;

    var successCount = 0, failCount = 0;
    var startTime = Date.now();

    var callback = function(response) {
        if (response.statusCode === 200) {
            successCount++;
        } else {
            failCount++;
        }

        if (successCount + failCount === testCount) {
            var endTime = Date.now();
            res.json({"success": successCount, "fail": failCount, "time": endTime - startTime});
        }
    };

    var itemId1 = "1f9e7891bffb03605e3a9b43f996f6ea";
    var itemId2 = "9dce21273d13dc1dcb1b47370359e753";
    for (var i = 0; i < testCount; i++) {
        http.get({
            host: req.get('host'),
            path: "/items/" + (i % 2 ? itemId1 : itemId2)
	}, callback);
    }
*/
};

//Create and populate or delete the database.
exports.dbOptions = function(req, res) {
    var option = req.params.option.toLowerCase();
    if (option === 'create') {
        db.cloudant.db.create('items', function(err/*, body*/) {
            if (!err) {
                db.populateDB();
                res.send({msg:'Successfully created database and populated!'});
            } else {
                res.send({msg:err});
            }
        });
    } else if (option === 'delete') {
        db.cloudant.db.destroy('items', function(err/*, body*/) {
	        if (!err) {
	            res.send({msg:'Successfully deleted db items!'});
	        } else {
	        	res.send({msg:'Error deleting db items: ' + err});
        	}
        });
    } else {
    	res.send({msg: 'your option was not understood. Please use "create" or "delete"'});
	}
};

//Create an item to add to the database.
exports.create = function(req, res) {
    db.itemsDb.insert(req.body, function(err/*, body, headers*/) {
        if (!err) {
            res.send({msg: 'Successfully created item'});
        } else {
            res.send({msg: 'Error on insert, maybe the item already exists: ' + err});
        }
    });
};

//find an item by ID.
exports.find = function(req, res) {
    var id = req.params.id;
    if (USE_FASTCACHE) {
    	var idAsNumber = parseInt(id.substring(id.length - 2), 16);
    	if (!idAsNumber || idAsNumber % 3 === 2) {
        	res.status(500).send({msg: 'server error'});
    	} else {
    		res.status(200).send({msg: 'all good'});
    	}
        return;
    }
    db.itemsDb.get(id, { revs_info: false }, function(err, body) {
        if (!err) {
            res.send(body);
        } else {
            res.send({msg:'Error: could not find item: ' + id});
        }
    });
};

//list all the database contents in order by product name
exports.list = function(req, res) {
    db.itemsDb.view('products', 'products_by_name', {include_docs:true}, function(err, body/*, headers*/) {
        if (!err) {
            res.send(body);
            return;
        }
        res.send({msg:'Error listing items: ' + err});
    });
};

//update an item using an ID.
exports.update = function(req, res) {
    var id = req.params.id;
    var data = req.body;
    db.itemsDb.get(id, {revs_info:true}, function(err, body) {
        if (!err) {
            data._rev = body._rev;
            db.itemsDb.insert(data, id, function(err/*, body, headers*/) {
	            if (!err) {
	                res.send({msg:'Successfully updated item: ' + JSON.stringify(data)});
	            } else {
	            	res.send({msg:'Error inserting for update: ' + err});
	        	}
            });
        }
        else {
        	res.send({msg:'Error getting item for update: ' + err});
    	}
    });
};

//remove an item from the database using an ID.
exports.remove =  function(req, res) {
    var id = req.params.id;
    db.itemsDb.get(id, { revs_info: true }, function(err, body) {
        if (!err) {
            //console.log('Deleting item: ' + id);
            db.itemsDb.destroy(id, body._rev, function(err/*, body*/) {
                if (!err) {
                    res.send({msg:'Successfully deleted item'});
                } else {
                    res.send({msg:'Error in delete: ' + err});
                }
            });
        } else {
            res.send({msg:'Error getting item id: ' + err});
        }
    });
};

//calculate the fibonacci of 20.
var fib = function(n) {
    if (n < 2) {
        return 1;
    }
    return fib(n - 2) + fib(n - 1);
};
exports.fib = function(req, res) {
    res.send({msg:'Done with fibonacci of 20: ' + fib(20)});
};

exports.getFastCache = function() {
    return USE_FASTCACHE;
};
<commit_msg>fixes hmagph/ui-feb17-01-onlinestore-master#1<commit_after>/*eslint-env node */
var http = require('http');
var db = require('./db');
db.initDB();
var USE_FASTCACHE = false;

/*
 * To enable the load generator and 'improved' cache mechanism below:
 * 1. remove the 'res.json({"success": 0, "fail": 0, "time": 0});' line
 * 2. uncomment the remaining method body
 */
exports.loadTest = function(req, res) {
//    res.json({"success": 0, "fail": 0, "time": 0});
///*
    USE_FASTCACHE = true;
    var testCount = req.query.count;
    testCount = testCount ? parseInt(testCount) : 100;

    var successCount = 0, failCount = 0;
    var startTime = Date.now();

    var callback = function(response) {
        if (response.statusCode === 200) {
            successCount++;
        } else {
            failCount++;
        }

        if (successCount + failCount === testCount) {
            var endTime = Date.now();
            res.json({"success": successCount, "fail": failCount, "time": endTime - startTime});
        }
    };

    var itemId1 = "1f9e7891bffb03605e3a9b43f996f6ea";
    var itemId2 = "9dce21273d13dc1dcb1b47370359e753";
    for (var i = 0; i < testCount; i++) {
        http.get({
            host: req.get('host'),
            path: "/items/" + (i % 2 ? itemId1 : itemId2)
	}, callback);
    }
//*/
};

//Create and populate or delete the database.
exports.dbOptions = function(req, res) {
    var option = req.params.option.toLowerCase();
    if (option === 'create') {
        db.cloudant.db.create('items', function(err/*, body*/) {
            if (!err) {
                db.populateDB();
                res.send({msg:'Successfully created database and populated!'});
            } else {
                res.send({msg:err});
            }
        });
    } else if (option === 'delete') {
        db.cloudant.db.destroy('items', function(err/*, body*/) {
	        if (!err) {
	            res.send({msg:'Successfully deleted db items!'});
	        } else {
	        	res.send({msg:'Error deleting db items: ' + err});
        	}
        });
    } else {
    	res.send({msg: 'your option was not understood. Please use "create" or "delete"'});
	}
};

//Create an item to add to the database.
exports.create = function(req, res) {
    db.itemsDb.insert(req.body, function(err/*, body, headers*/) {
        if (!err) {
            res.send({msg: 'Successfully created item'});
        } else {
            res.send({msg: 'Error on insert, maybe the item already exists: ' + err});
        }
    });
};

//find an item by ID.
exports.find = function(req, res) {
    var id = req.params.id;
    if (USE_FASTCACHE) {
    	var idAsNumber = parseInt(id.substring(id.length - 2), 16);
    	if (!idAsNumber || idAsNumber % 3 === 2) {
        	res.status(500).send({msg: 'server error'});
    	} else {
    		res.status(200).send({msg: 'all good'});
    	}
        return;
    }
    db.itemsDb.get(id, { revs_info: false }, function(err, body) {
        if (!err) {
            res.send(body);
        } else {
            res.send({msg:'Error: could not find item: ' + id});
        }
    });
};

//list all the database contents in order by product name
exports.list = function(req, res) {
    db.itemsDb.view('products', 'products_by_name', {include_docs:true}, function(err, body/*, headers*/) {
        if (!err) {
            res.send(body);
            return;
        }
        res.send({msg:'Error listing items: ' + err});
    });
};

//update an item using an ID.
exports.update = function(req, res) {
    var id = req.params.id;
    var data = req.body;
    db.itemsDb.get(id, {revs_info:true}, function(err, body) {
        if (!err) {
            data._rev = body._rev;
            db.itemsDb.insert(data, id, function(err/*, body, headers*/) {
	            if (!err) {
	                res.send({msg:'Successfully updated item: ' + JSON.stringify(data)});
	            } else {
	            	res.send({msg:'Error inserting for update: ' + err});
	        	}
            });
        }
        else {
        	res.send({msg:'Error getting item for update: ' + err});
    	}
    });
};

//remove an item from the database using an ID.
exports.remove =  function(req, res) {
    var id = req.params.id;
    db.itemsDb.get(id, { revs_info: true }, function(err, body) {
        if (!err) {
            //console.log('Deleting item: ' + id);
            db.itemsDb.destroy(id, body._rev, function(err/*, body*/) {
                if (!err) {
                    res.send({msg:'Successfully deleted item'});
                } else {
                    res.send({msg:'Error in delete: ' + err});
                }
            });
        } else {
            res.send({msg:'Error getting item id: ' + err});
        }
    });
};

//calculate the fibonacci of 20.
var fib = function(n) {
    if (n < 2) {
        return 1;
    }
    return fib(n - 2) + fib(n - 1);
};
exports.fib = function(req, res) {
    res.send({msg:'Done with fibonacci of 20: ' + fib(20)});
};

exports.getFastCache = function() {
    return USE_FASTCACHE;
};
<|endoftext|>


<commit_before>require('./db');
initDB();

var USE_FASTCACHE = true;

var http = require('http');

//Create and populate or delete the database.
exports.dbOptions = function(req, res) {
    var option = req.params.option.toLowerCase();
    if(option === 'create'){
        cloudant.db.create('items', function(err, body){
            if(!err){
                populateDB();
                res.send({msg:'Successfully created database and populated!'});
            }
            else{
                res.send({msg:err});
            }
        });
    }
    else if(option === 'delete'){
        cloudant.db.destroy('items',function(err, body){
        if(!err){
            res.send({msg:'Successfully deleted db items!'});
        }
        else res.send({msg:'Error deleting db items: ' + err});
        });
    }
    else res.send({msg: 'your option was not understood. Please use "create" or "delete"'});
}

//Create an item to add to the database.
exports.create = function(req, res) {
        db.insert(req.body, function (err, body, headers) {
            if (!err) {
                res.send({msg: 'Successfully created item'});
            }
            else {
                res.send({msg: 'Error on insert, maybe the item already exists: ' + err});
            }
        });
    }

//find an item by ID.
exports.find = function(req, res) {
    var id = req.params.id;
    if (USE_FASTCACHE) {
    	var idAsNumber = parseInt(id.substring(id.length - 2), 16);
    	if (!idAsNumber || idAsNumber % 3 === 2) {
        	res.status(500).send({msg: 'server error'});
    	} else {
    		res.status(200).send({msg: 'all good'});
    	}
        return;
    }

    db.get(id, { revs_info: false }, function(err, body) {
        if (!err){
            res.send(body);
        }
        else{
            res.send({msg:'Error: could not find item: ' + id});
        }
    });
}

//list all the database contents.
exports.list = function(req, res) {
    db.list({include_docs: true}, function (err, body, headers) {
    if (!err) {
        res.send(body);
        return;
    }
    else res.send({msg:'Error listing items: ' + err});
    });
}

//update an item using an ID.
exports.update = function(req, res) {
    var id = req.params.id;
    var data = req.body;
    db.get(id,{revs_info:true}, function (err, body) {
        if(!err){
            data._rev = body._rev;
            db.insert(data, id, function(err, body, headers){
            if(!err){
                res.send({msg:'Successfully updated item: ' + JSON.stringify(data)});
            }
            else res.send({msg:'Error inserting for update: ' + err});
            });
        }
        else res.send({msg:'Error getting item for update: ' + err});
    });
}

//remove an item from the database using an ID.
exports.remove =  function(req, res){
    var id = req.params.id;
    db.get(id, { revs_info: true }, function(err, body) {
        if (!err){
            //console.log('Deleting item: ' + id);
            db.destroy(id, body._rev, function(err, body){
                if(!err){
                    res.send({msg:'Successfully deleted item'});
                }
                else{
                    res.send({msg:'Error in delete: ' + err});
                }
            })
        }
        else{
            res.send({msg:'Error getting item id: ' + err});
        }
    });
}

//calculate the fibonacci of 20.
exports.fib = function(req, res) {
    res.send({msg:'Done with fibonacci of 20: ' + fib(20)});
}

var fib = function(n) {
    if (n < 2) {
        return 1;
    }
    else {
        return (fib(n - 2) + fib(n - 1));
    }
}

exports.loadTest = function(req, res) {
    // *************** (1 of 3) comment the next line to get the full loadTest function ***********
 //  res.json({"success": 0, "fail": 0, "time": 0}); /*
    var testCount = req.query.count;
    testCount = testCount ? parseInt(testCount) : 100;

    var successCount = 0, failCount = 0;
    var startTime = Date.now();

    var callback = function(response) {
        if (response.statusCode === 200) {
            successCount++;
        } else {
            failCount++;
        }

        if (successCount + failCount === testCount) {
            var endTime = Date.now();
            res.json({"success": successCount, "fail": failCount, "time": endTime - startTime});
        }
    };

	var itemId1 = "1f9e7891bffb03605e3a9b43f996f6ea";
	var itemId2 = "9dce21273d13dc1dcb1b47370359e753";
    for (var i = 0; i < testCount; i++) {
		http.get({
	        host: req.get('host'),
	        path: "/items/" + (i % 2 ? itemId1 : itemId2)
	    }, callback);
    }

// *************** (2 of 3) comment the next line to get the full loadTest function ***********
//*/
// *************** (3 of 3) change USE_FASTCACHE up at the top to 'true' to enable enhanced lookup ***********
};
<commit_msg>Update items.js<commit_after>require('./db');
initDB();

var USE_FASTCACHE = false;

var http = require('http');

//Create and populate or delete the database.
exports.dbOptions = function(req, res) {
    var option = req.params.option.toLowerCase();
    if(option === 'create'){
        cloudant.db.create('items', function(err, body){
            if(!err){
                populateDB();
                res.send({msg:'Successfully created database and populated!'});
            }
            else{
                res.send({msg:err});
            }
        });
    }
    else if(option === 'delete'){
        cloudant.db.destroy('items',function(err, body){
        if(!err){
            res.send({msg:'Successfully deleted db items!'});
        }
        else res.send({msg:'Error deleting db items: ' + err});
        });
    }
    else res.send({msg: 'your option was not understood. Please use "create" or "delete"'});
}

//Create an item to add to the database.
exports.create = function(req, res) {
        db.insert(req.body, function (err, body, headers) {
            if (!err) {
                res.send({msg: 'Successfully created item'});
            }
            else {
                res.send({msg: 'Error on insert, maybe the item already exists: ' + err});
            }
        });
    }

//find an item by ID.
exports.find = function(req, res) {
    var id = req.params.id;
    if (USE_FASTCACHE) {
    	var idAsNumber = parseInt(id.substring(id.length - 2), 16);
    	if (!idAsNumber || idAsNumber % 3 === 2) {
        	res.status(500).send({msg: 'server error'});
    	} else {
    		res.status(200).send({msg: 'all good'});
    	}
        return;
    }

    db.get(id, { revs_info: false }, function(err, body) {
        if (!err){
            res.send(body);
        }
        else{
            res.send({msg:'Error: could not find item: ' + id});
        }
    });
}

//list all the database contents.
exports.list = function(req, res) {
    db.list({include_docs: true}, function (err, body, headers) {
    if (!err) {
        res.send(body);
        return;
    }
    else res.send({msg:'Error listing items: ' + err});
    });
}

//update an item using an ID.
exports.update = function(req, res) {
    var id = req.params.id;
    var data = req.body;
    db.get(id,{revs_info:true}, function (err, body) {
        if(!err){
            data._rev = body._rev;
            db.insert(data, id, function(err, body, headers){
            if(!err){
                res.send({msg:'Successfully updated item: ' + JSON.stringify(data)});
            }
            else res.send({msg:'Error inserting for update: ' + err});
            });
        }
        else res.send({msg:'Error getting item for update: ' + err});
    });
}

//remove an item from the database using an ID.
exports.remove =  function(req, res){
    var id = req.params.id;
    db.get(id, { revs_info: true }, function(err, body) {
        if (!err){
            //console.log('Deleting item: ' + id);
            db.destroy(id, body._rev, function(err, body){
                if(!err){
                    res.send({msg:'Successfully deleted item'});
                }
                else{
                    res.send({msg:'Error in delete: ' + err});
                }
            })
        }
        else{
            res.send({msg:'Error getting item id: ' + err});
        }
    });
}

//calculate the fibonacci of 20.
exports.fib = function(req, res) {
    res.send({msg:'Done with fibonacci of 20: ' + fib(20)});
}

var fib = function(n) {
    if (n < 2) {
        return 1;
    }
    else {
        return (fib(n - 2) + fib(n - 1));
    }
}

exports.loadTest = function(req, res) {
    // *************** (1 of 3) comment the next line to get the full loadTest function ***********
 //  res.json({"success": 0, "fail": 0, "time": 0}); /*
    var testCount = req.query.count;
    testCount = testCount ? parseInt(testCount) : 100;

    var successCount = 0, failCount = 0;
    var startTime = Date.now();

    var callback = function(response) {
        if (response.statusCode === 200) {
            successCount++;
        } else {
            failCount++;
        }

        if (successCount + failCount === testCount) {
            var endTime = Date.now();
            res.json({"success": successCount, "fail": failCount, "time": endTime - startTime});
        }
    };

	var itemId1 = "1f9e7891bffb03605e3a9b43f996f6ea";
	var itemId2 = "9dce21273d13dc1dcb1b47370359e753";
    for (var i = 0; i < testCount; i++) {
		http.get({
	        host: req.get('host'),
	        path: "/items/" + (i % 2 ? itemId1 : itemId2)
	    }, callback);
    }

// *************** (2 of 3) comment the next line to get the full loadTest function ***********
//*/
// *************** (3 of 3) change USE_FASTCACHE up at the top to 'true' to enable enhanced lookup ***********
};
<|endoftext|>


<commit_before><commit_msg>working on login route<commit_after>const express = require('express')
const router = express.Router()
const knex = require('../knex')
const bcrypt = require('bcrypt')

router.post('/', function (req, res, next) {
  const { email, password } = req.body

  knex('owners')
    .where('email', email)

})

router.get('/', function (req, res, next) {
  // code goes here
})
<|endoftext|>


<commit_before>/**
 * Created by sghaida on 5/12/2017.
 */

var express     = require('express'),
    passport    = require('passport'),
    router = express.Router();

router.get('/', function(req, res, next) {
    res.render('login');
});

router.post('/', passport.authenticate('ldapauth', {
        session: true,
        successReturnToOrRedirect: '/',
        failureRedirect: '/login'
    }),
    function(req, res) {
        // var returnTo = '/'
        // if (req.session.returnTo) {
        //     returnTo = req.session.returnTo
        //     delete req.session.returnTo
        // }
        //console.log(res)
        //res.send({status: 'ok'});
    }
);

module.exports = router;<commit_msg>cleanup<commit_after>/**
 * Created by sghaida on 5/12/2017.
 */

var express     = require('express'),
    passport    = require('passport'),
    User        = require('../models/user')
    router = express.Router();

router.get('/', function(req, res, next) {
    res.render('login');
});

router.post('/', passport.authenticate('ldapauth', {
        session: true,
        successReturnToOrRedirect: '/',
        failureRedirect: '/login',
    })
);

module.exports = router;<|endoftext|>


<commit_before>'use strict';

var mediaQuery = require('css-mediaquery'),
    rework     = require('rework'),
    grids      = require('rework-pure-grids'),
    hbs        = require('../lib/hbs'),
    utils      = require('../lib/utils'),
    middleware = require('../middleware');

exports.index = [middleware.exposeTemplates('start'), showStart];

// -----------------------------------------------------------------------------

/*
    Routes for /start/ could be any of the following:
    * `/start/`
    * `/start/?cols=6&med=48em&lrg=60em`
    * `/start/?cols=6&sm=screen and (min-device-width: 480px)`
*/
function showStart (req, res, next) {

    var query = normalizeQuery(utils.extend({}, req.query));

    if (isBelowColLimit(query.cols) && isBelowMqLimit(query.mediaQueries)) {
        query.css = rework('').use(grids.units(query.cols, {
            mediaQueries: query.mediaQueries.reduce(function (prev, curr) {
                prev[curr.id] = curr.value;
                return prev;
            }, {})
        })).toString();

        res.expose(query, 'start.query');
        res.expose({
            isBelowColLimit: isBelowColLimit,
            isBelowMqLimit: isBelowMqLimit
        }, 'start.utils');

        res.render('start', query);
    }
    else {
        if (!res.locals.message) {
            res.locals.message = 'To protect our servers from being overloaded, our online tool can only generate up to 100 columns and 20 media queries. Try again with a lower number of columns or media queries.';
        }
        next(utils.error(400));
    }
}

// Takes in a string input for number of columns and converts it into an array.
function normalizeCols (cols) {
    //cols will always be a string, so we can convert the string to an array of 1 or more integers.
    return cols.split(',').map(function (x) {
        return parseInt(x, 10);
    });
}

function isBelowColLimit (cols) {
    if (cols) {
        return (cols <= 100);
    }
    return true;

}

function isBelowMqLimit (mq) {
    if (mq && mq.length) {
        return (mq.length <= 20);
    }
    return true;
}

/*
Checks to see if media queries are valid, by following these steps:
    Does the query param value parse as a media query?
        If yes? return true.
        If not, then assume it's a width value, so wrap it with "screen and (min-width: " + value + ")"
    Does it now parse as a media query?
        If yes, return true.
        If not, return false.
*/
function isValidMQ (mqStr) {
    //This regex splits up a string that contains a sequences of letters or numbers ("48em", "480px") into an array of grouped letters and numbers (["48", "em"], ["480", "px"])
    var RE_SEPARATE_NUM_LETTERS = /[a-zA-Z]+|[0-9]+/g,
        captures;
    try {
        mediaQuery.parse(mqStr);
    } catch (e) {
        //invalid media query, so let's check that there's some floated value in here, and if there is, we will prepend/append some strings
        captures = mqStr.match(RE_SEPARATE_NUM_LETTERS);
        if (captures.length && captures.length === 2 && parseFloat(captures[0])) {
            mqStr = 'screen and (min-width: ' + mqStr + ')';
        }

        else {
            return false;
        }
        try {
            mediaQuery.parse(mqStr);
        } catch (e) {
            //still not a valid media query
            return false;
        }
    }

    return mqStr;
}

/*
    This function takes in a `req.query` object, validates all the media queries within it, removes the incorrect media queries, and then returns a modified `req.query` object, with only valid values within in.
*/
function normalizeQuery (obj) {
    var query = obj,
        mq = utils.extend({}, query);

    delete mq.cols;
    delete mq.prefix;

    query.mediaQueries = [];

    //remove the media query from `query`, and add it as an array element if it's valid.
    Object.keys(mq).forEach(function (key) {
        var mqStr = isValidMQ(mq[key]);
        if (mqStr) {
            query.mediaQueries.push({id: key, value: mqStr});
        }
        delete query[key];
    });

    if (query.cols) {
        query.cols = normalizeCols(query.cols);
    }
    return query;
}
<commit_msg>send constants over express-state instead of functions<commit_after>'use strict';

var mediaQuery = require('css-mediaquery'),
    rework     = require('rework'),
    grids      = require('rework-pure-grids'),
    hbs        = require('../lib/hbs'),
    utils      = require('../lib/utils'),
    middleware = require('../middleware'),
    COL_LIMIT  = 100,
    MQ_LIMIT   = 10;

exports.index = [middleware.exposeTemplates('start'), showStart];

// -----------------------------------------------------------------------------

/*
    Routes for /start/ could be any of the following:
    * `/start/`
    * `/start/?cols=6&med=48em&lrg=60em`
    * `/start/?cols=6&sm=screen and (min-device-width: 480px)`
*/
function showStart (req, res, next) {

    console.log(req.query);

    var query = normalizeQuery(utils.extend({}, req.query));

    if (isBelowColLimit(query.cols) && isBelowMqLimit(query.mediaQueries)) {
        query.css = rework('').use(grids.units(query.cols, {
            mediaQueries: query.mediaQueries.reduce(function (prev, curr) {
                prev[curr.id] = curr.value;
                return prev;
            }, {})
        })).toString();

        res.expose(query, 'start.query');
        res.expose({
            colLimit: COL_LIMIT,
            mqLimit: MQ_LIMIT
        }, 'start.constants');

        res.render('start', query);
    }
    else {
        if (!res.locals.message) {
            res.locals.message = 'To protect our servers from being overloaded, our online tool can only generate up to 100 columns and 20 media queries. Try again with a lower number of columns or media queries.';
        }
        next(utils.error(400));
    }
}

// Takes in a string input for number of columns and converts it into an array.
function normalizeCols (cols) {
    //cols will always be a string, so we can convert the string to an array of 1 or more integers.
    return cols.split(',').map(function (x) {
        return parseInt(x, 10);
    });
}

function isBelowColLimit (cols) {
    if (cols) {
        return (cols <= COL_LIMIT);
    }
    return true;

}

function isBelowMqLimit (mq) {
    if (mq && mq.length) {
        return (mq.length <= MQ_LIMIT);
    }
    return true;
}

/*
Checks to see if media queries are valid, by following these steps:
    Does the query param value parse as a media query?
        If yes? return true.
        If not, then assume it's a width value, so wrap it with "screen and (min-width: " + value + ")"
    Does it now parse as a media query?
        If yes, return true.
        If not, return false.
*/
function isValidMQ (mqStr) {
    //This regex splits up a string that contains a sequences of letters or numbers ("48em", "480px") into an array of grouped letters and numbers (["48", "em"], ["480", "px"])
    var RE_SEPARATE_NUM_LETTERS = /[a-zA-Z]+|[0-9]+/g,
        captures;
    try {
        mediaQuery.parse(mqStr);
    } catch (e) {
        //invalid media query, so let's check that there's some floated value in here, and if there is, we will prepend/append some strings
        captures = mqStr.match(RE_SEPARATE_NUM_LETTERS);
        if (captures.length && captures.length === 2 && parseFloat(captures[0])) {
            mqStr = 'screen and (min-width: ' + mqStr + ')';
        }

        else {
            return false;
        }
        try {
            mediaQuery.parse(mqStr);
        } catch (e) {
            //still not a valid media query
            return false;
        }
    }

    return mqStr;
}

/*
    This function takes in a `req.query` object, validates all the media queries within it, removes the incorrect media queries, and then returns a modified `req.query` object, with only valid values within in.
*/
function normalizeQuery (obj) {
    var query = obj,
        mq = utils.extend({}, query);

    delete mq.cols;
    delete mq.prefix;

    query.mediaQueries = [];

    //remove the media query from `query`, and add it as an array element if it's valid.
    Object.keys(mq).forEach(function (key) {
        var mqStr = isValidMQ(mq[key]);
        if (mqStr) {
            query.mediaQueries.push({id: key, value: mqStr});
        }
        delete query[key];
    });

    if (query.cols) {
        query.cols = normalizeCols(query.cols);
    }
    return query;
}
<|endoftext|>


<commit_before>'use strict';

var archiver   = require('archiver'),
    mediaQuery = require('css-mediaquery'),
    rework     = require('rework'),
    grids      = require('rework-pure-grids'),
    path       = require('path');

var config     = require('../config'),
    hbs        = require('../lib/hbs'),
    stripmq    = require('../lib/stripmq'),
    utils      = require('../lib/utils'),
    middleware = require('../middleware');

exports.index = [
    normalizeOptions,
    middleware.exposeTemplates('start'),
    generateCSS,
    showStart
];

exports.css = [
    normalizeOptions,
    generateCSS,
    sendCSS
];

exports.download = [
    normalizeOptions,
    generateCSS,
    generateHTML,
    downloadStart
];

// -----------------------------------------------------------------------------

var LIMITS = {
    cols        : {min: 2, max: 100},
    prefix      : {min: 0, max: 20},
    mediaQueries: {min: 0, max: 10}
};

function normalizeOptions(req, res, next) {
    var mediaQueries = [],
        cols, prefix;

    function badRequest(label, message) {
        res.locals.message = message;
        throw utils.error(400, 'Bad Request: ' + label);
    }

    Object.keys(req.query).forEach(function (param) {
        var val = req.query[param];

        if (Array.isArray(val)) {
            badRequest('Duplicate param',
                '"' + param + '" must only have a single value.');
        }

        switch (param.toLowerCase()) {
            case 'cols':
                val = parseInt(val, 10);

                if (val < LIMITS.cols.min || val > LIMITS.cols.max) {
                    badRequest('Column range',
                        '"cols" must be between 2—100, inclusively.');
                }

                cols = val;

                break;

            case 'prefix':
                if (val.length > LIMITS.prefix.max) {
                    badRequest('Prefix length',
                        '"prefix" must be between 0—20 characters.');
                }

                prefix = val;

                break;

            // Assume it's a media query.
            default:
                try {
                    val = normalizeMediaQuery(val);
                } catch (e) {
                    badRequest('Media Query',
                        'Invalid CSS Media Query: "' + val + '".');
                }

                mediaQueries.push({
                    id: param,
                    mq: val
                });

                break;
        }
    });

    if (mediaQueries.length > LIMITS.mediaQueries.max) {
        badRequest('Media Query',
            'More than 10 CSS Media Queries were provided.');
    }

    req.startOptions = {
        cols        : cols,
        prefix      : prefix,
        mediaQueries: mediaQueries
    };
    next();
}

function normalizeMediaQuery(mq, options) {
    mq = mq.trim();
    var expand = options && options.expand;

    if (expand) {
        mq = 'screen and (min-width: ' + mq + ')';
    }

    try {
        mediaQuery.parse(mq);
        return mq;
    } catch (e) {
        // When we've already expanded the short-hand MQ syntax, or when the
        // short-hand form doesn't look like a length value, re-throw the error.
        if (expand || !/^(\d|\.)/.test(mq)) {
            throw e;
        }
    }

    // Try again, this time expanding the `mq` assuming it's in the short-hand.
    return normalizeMediaQuery(mq, {expand: true});
}

function generateHTML(req, res, next) {
    var template = path.join(config.dirs.shared, 'start', 'html' + hbs.extname);

    hbs.render(template, {
        cache   : req.app.enabled('view cache'),
        pure    : config.pure,
        needsCSS: res.needsCSS,
        css     : res.css
    }, function (err, html) {
        if (err) { return next(err); }
        res.html = html;
        next();
    });
}

function generateCSS(req, res, next) {
    var defaults     = res.locals.pure.responsive,
        startOptions = req.startOptions,
        mediaQueries = startOptions.mediaQueries,
        numMQs       = mediaQueries.length,
        gridsGenOpts = {},
        genGridsCSS  = false;

    if ((startOptions.cols && startOptions.cols !== defaults.cols) ||
        (numMQs && numMQs !== defaults.mediaQueries.length)) {

        genGridsCSS = true;
    }

    if (startOptions.prefix && startOptions.prefix !== defaults.prefix) {
        genGridsCSS = true;
        gridsGenOpts.selectorPrefix = startOptions.prefix;
    }

    gridsGenOpts.mediaQueries = mediaQueries.reduce(function (mqs, mq, i) {
        var dmq = defaults.mediaQueries[i];

        if (!(dmq && dmq.id === mq.id && dmq.mq === mq.mq)) {
            genGridsCSS = true;
        }

        mqs[mq.id] = mq.mq;
        return mqs;
    }, {});

    res.needsCSS = genGridsCSS || !!numMQs;

    if (genGridsCSS) {
        res.css = rework('')
                .use(grids.units(startOptions.cols, gridsGenOpts))
                .toString({indent: '    '});

        if (numMQs) {
            res.cssOldIE = rework(res.css)
                    .use(stripmq())
                    .toString({indent: '    '});
        }
    }
    else {
        res.css = null;
        res.cssOldIE = null;
    }

    next();
}

function showStart(req, res, next) {
    var pure         = res.locals.pure,
        defaults     = pure.responsive,
        startOptions = req.startOptions;

    res.locals.needsCSS = res.needsCSS;
    res.locals.css      = res.css;
    res.locals.cssOldIE = res.cssOldIE;
    res.locals.query    = req._parsedUrl.search;

    res.locals(startOptions);

    res.expose(pure.version, 'pure.version');
    res.expose(LIMITS,       'start.limits');
    res.expose(defaults,     'start.defaults');
    res.expose(startOptions, 'start.options');

    res.render('start');
}

function sendCSS(req, res, next) {
    res.json({
        css     : res.css,
        cssOldIE: res.cssOldIE
    });
}

function downloadStart(req, res, next) {
    var archive = archiver('zip');

    archive.append(res.html, {name: 'index.html'});

    if (res.css) {
        archive.append(res.css, {name: 'grid.css'});
    }

    if (res.cssOldIE) {
        archive.append(res.cssOldIE, {name: 'grid-old-ie.css'});
    }

    res.set('Content-Disposition', 'attachment; filename="pure-start.zip"');
    archive.finalize().pipe(res);
}
<commit_msg>move code from else block and make it the default<commit_after>'use strict';

var archiver   = require('archiver'),
    mediaQuery = require('css-mediaquery'),
    rework     = require('rework'),
    grids      = require('rework-pure-grids'),
    path       = require('path');

var config     = require('../config'),
    hbs        = require('../lib/hbs'),
    stripmq    = require('../lib/stripmq'),
    utils      = require('../lib/utils'),
    middleware = require('../middleware');

exports.index = [
    normalizeOptions,
    middleware.exposeTemplates('start'),
    generateCSS,
    showStart
];

exports.css = [
    normalizeOptions,
    generateCSS,
    sendCSS
];

exports.download = [
    normalizeOptions,
    generateCSS,
    generateHTML,
    downloadStart
];

// -----------------------------------------------------------------------------

var LIMITS = {
    cols        : {min: 2, max: 100},
    prefix      : {min: 0, max: 20},
    mediaQueries: {min: 0, max: 10}
};

function normalizeOptions(req, res, next) {
    var mediaQueries = [],
        cols, prefix;

    function badRequest(label, message) {
        res.locals.message = message;
        throw utils.error(400, 'Bad Request: ' + label);
    }

    Object.keys(req.query).forEach(function (param) {
        var val = req.query[param];

        if (Array.isArray(val)) {
            badRequest('Duplicate param',
                '"' + param + '" must only have a single value.');
        }

        switch (param.toLowerCase()) {
            case 'cols':
                val = parseInt(val, 10);

                if (val < LIMITS.cols.min || val > LIMITS.cols.max) {
                    badRequest('Column range',
                        '"cols" must be between 2—100, inclusively.');
                }

                cols = val;

                break;

            case 'prefix':
                if (val.length > LIMITS.prefix.max) {
                    badRequest('Prefix length',
                        '"prefix" must be between 0—20 characters.');
                }

                prefix = val;

                break;

            // Assume it's a media query.
            default:
                try {
                    val = normalizeMediaQuery(val);
                } catch (e) {
                    badRequest('Media Query',
                        'Invalid CSS Media Query: "' + val + '".');
                }

                mediaQueries.push({
                    id: param,
                    mq: val
                });

                break;
        }
    });

    if (mediaQueries.length > LIMITS.mediaQueries.max) {
        badRequest('Media Query',
            'More than 10 CSS Media Queries were provided.');
    }

    req.startOptions = {
        cols        : cols,
        prefix      : prefix,
        mediaQueries: mediaQueries
    };
    next();
}

function normalizeMediaQuery(mq, options) {
    mq = mq.trim();
    var expand = options && options.expand;

    if (expand) {
        mq = 'screen and (min-width: ' + mq + ')';
    }

    try {
        mediaQuery.parse(mq);
        return mq;
    } catch (e) {
        // When we've already expanded the short-hand MQ syntax, or when the
        // short-hand form doesn't look like a length value, re-throw the error.
        if (expand || !/^(\d|\.)/.test(mq)) {
            throw e;
        }
    }

    // Try again, this time expanding the `mq` assuming it's in the short-hand.
    return normalizeMediaQuery(mq, {expand: true});
}

function generateHTML(req, res, next) {
    var template = path.join(config.dirs.shared, 'start', 'html' + hbs.extname);

    hbs.render(template, {
        cache   : req.app.enabled('view cache'),
        pure    : config.pure,
        needsCSS: res.needsCSS,
        css     : res.css
    }, function (err, html) {
        if (err) { return next(err); }
        res.html = html;
        next();
    });
}

function generateCSS(req, res, next) {
    var defaults     = res.locals.pure.responsive,
        startOptions = req.startOptions,
        mediaQueries = startOptions.mediaQueries,
        numMQs       = mediaQueries.length,
        gridsGenOpts = {},
        genGridsCSS  = false;

    if ((startOptions.cols && startOptions.cols !== defaults.cols) ||
        (numMQs && numMQs !== defaults.mediaQueries.length)) {

        genGridsCSS = true;
    }

    if (startOptions.prefix && startOptions.prefix !== defaults.prefix) {
        genGridsCSS = true;
        gridsGenOpts.selectorPrefix = startOptions.prefix;
    }

    gridsGenOpts.mediaQueries = mediaQueries.reduce(function (mqs, mq, i) {
        var dmq = defaults.mediaQueries[i];

        if (!(dmq && dmq.id === mq.id && dmq.mq === mq.mq)) {
            genGridsCSS = true;
        }

        mqs[mq.id] = mq.mq;
        return mqs;
    }, {});

    res.needsCSS = genGridsCSS || !!numMQs;
    res.css      = null;
    res.cssOldIE = null;

    if (genGridsCSS) {
        res.css = rework('')
                .use(grids.units(startOptions.cols, gridsGenOpts))
                .toString({indent: '    '});

        if (numMQs) {
            res.cssOldIE = rework(res.css)
                    .use(stripmq())
                    .toString({indent: '    '});
        }
    }

    next();
}

function showStart(req, res, next) {
    var pure         = res.locals.pure,
        defaults     = pure.responsive,
        startOptions = req.startOptions;

    res.locals.needsCSS = res.needsCSS;
    res.locals.css      = res.css;
    res.locals.cssOldIE = res.cssOldIE;
    res.locals.query    = req._parsedUrl.search;

    res.locals(startOptions);

    res.expose(pure.version, 'pure.version');
    res.expose(LIMITS,       'start.limits');
    res.expose(defaults,     'start.defaults');
    res.expose(startOptions, 'start.options');

    res.render('start');
}

function sendCSS(req, res, next) {
    res.json({
        css     : res.css,
        cssOldIE: res.cssOldIE
    });
}

function downloadStart(req, res, next) {
    var archive = archiver('zip');

    archive.append(res.html, {name: 'index.html'});

    if (res.css) {
        archive.append(res.css, {name: 'grid.css'});
    }

    if (res.cssOldIE) {
        archive.append(res.cssOldIE, {name: 'grid-old-ie.css'});
    }

    res.set('Content-Disposition', 'attachment; filename="pure-start.zip"');
    archive.finalize().pipe(res);
}
<|endoftext|>


<commit_before>var express = require('express');
var router = express.Router();

/* GET users listing. */
router.get('/', function(req, res) {
    res.send('respond with a resource');
});

module.exports = router;
<commit_msg>Delete users.js<commit_after><|endoftext|>