1 var express = require('express');
  2 var router = express.Router();
  3 const bcrypt = require('bcryptjs');
  4 var jwt = require('jsonwebtoken');
  5 
  6 /**
  7 	* Function to handle GET requests for login page.
  8 	* Render the registration page, and return it through res.
  9 	* @param {Object} req The express routing HTTP client request object.
 10 	* @param {Object} res The express routing HTTP client response object.
 11 	* @return {Object} A JSON object that holds req and res.
 12 */
 13 var loginGet = function(req, res) {
 14 	res.render('login', {err: null});
 15 }
 16 
 17 router.get('/', loginGet);
 18 
 19 /**
 20 	* Function to handle POST requests for login page.
 21 	* Causes the server to return 400 error if malformed request.
 22 	* Queries MongoDB for this user. If it doesn't exist, or the password doesn't match
 23 	* with cryptographic hash, then causes the server to return a 401 error, and redirects to login.
 24 	* If all goes well, then redirects user to her profile page
 25 	* with a JSON web token that lasts two hours.
 26 	* @param {Object} req The express routing HTTP client request object,
 27 	* whose body contains the user's email and password.
 28 	* @param {Object} res The express routing HTTP client response object.
 29 	* @return {Object} A JSON object that holds req and res.
 30 */
 31 var loginPost = function(req, res) {
 32 	var usr, pw;
 33 	if (req.body.email === undefined || req.body.password === undefined) {
 34 		res.status(400).send('Bad request');
 35 		return;
 36 	}
 37 	usr = req.body.email;
 38 	pw = req.body.password;
 39 	var query = {email: usr};
 40 	req.app.locals.db.collection('Users').findOne(query, function(err, result) {
 41 		if(result === null) {
 42 			res.status(401).render('login', {err: 'Invalid email/password combination'});
 43 			return;
 44 		}
 45 		bcrypt.compare(pw, result.password, function(err, rs) {
 46 			if(rs == true) {
 47 				var payload = {"exp": Math.floor(Date.now() / 1000) + (2 * 60 * 60), "usr": usr, "userId": result.userId};
 48 				var header = {"alg": "HS256", "typ": "JWT"};
 49 				var cert = "C-UFRaksvPKhx1txJYFcut3QGxsafPmwCY6SCly3G6c";
 50 				jwt.sign(payload, cert, { algorithm: 'HS256',  header: header}, function(err, token) {
 51 					res.cookie("jwt", token, {});
 52 					res.redirect(`/active/profile/${result.userId}`);
 53 				});
 54 			}
 55 			else {
 56 				res.status(401).render('login', {err: 'Invalid email/password combination'});
 57 			}
 58 		});
 59 	});
 60 }
 61 
 62 router.post('/', loginPost);
 63 
 64 module.exports = router;
 65