From 0bd5933d97a90473233d0f90f465a43aba430ffa Mon Sep 17 00:00:00 2001
From: Benjamin Auder <benjamin.auder@somewhere>
Date: Wed, 9 Jan 2019 01:53:59 +0100
Subject: [PATCH] Roughly completed Users logic; untested

---
 .gitignore                          |  2 +-
 config/parameters.js.dist           | 25 ++++++++++++
 models/User.js                      | 35 +++++++++++------
 routes/all.js                       |  5 ++-
 routes/users.js                     | 60 ++++++++++++-----------------
 utils/{mailer.js.dist => mailer.js} | 22 ++++-------
 utils/tokenGenerator.js             | 17 ++++++++
 7 files changed, 103 insertions(+), 63 deletions(-)
 create mode 100644 config/parameters.js.dist
 rename utils/{mailer.js.dist => mailer.js} (76%)
 create mode 100644 utils/tokenGenerator.js

diff --git a/.gitignore b/.gitignore
index 8a553e65..6e4c9604 100644
--- a/.gitignore
+++ b/.gitignore
@@ -17,7 +17,7 @@ pids
 
 # Various files
 /db/vchess.sqlite
-/utils/mailer.js
+/config/parameters.js
 /public/javascripts/socket_url.js
 
 # CSS generated files
diff --git a/config/parameters.js.dist b/config/parameters.js.dist
new file mode 100644
index 00000000..944a6ee5
--- /dev/null
+++ b/config/parameters.js.dist
@@ -0,0 +1,25 @@
+var Parameters = { };
+
+// For mail sending. NOTE: *no trailing slash*
+Parameters.siteURL = "http://localhost:3000";
+
+// Lifespan of a (login) cookie
+Parameters.cookieExpire = 183*24*3600*1000; //6 months in milliseconds
+
+// Characters in a login token, and period of validity (in milliseconds)
+Parameters.token = {
+	length: 16,
+	expire: 1000*60*30, //30 minutes in milliseconds
+};
+
+// Email settings
+Parameters.mail = {
+	host: "mail_host_address",
+	port: 465, //if secure; otherwise use 587
+	secure: true, //...or false
+	user: "mail_user_name",
+	pass: "mail_password",
+	contact: "some_contact_email",
+};
+
+module.exports = Parameters;
diff --git a/models/User.js b/models/User.js
index 66b1bf54..777eeaa2 100644
--- a/models/User.js
+++ b/models/User.js
@@ -1,5 +1,6 @@
 var db = require("../utils/database");
 var maild = require("../utils/mailer.js");
+var TokenGen = require("../utils/tokenGenerator");
 
 /*
  * Structure:
@@ -32,7 +33,7 @@ exports.getOne = function(by, value, cb)
 	db.serialize(function() {
 		db.get(
 			"SELECT * FROM Users " +
-			"WHERE " + by " = " + delimiter + value + delimiter,
+			"WHERE " + by + " = " + delimiter + value + delimiter,
 			callback);
 	});
 }
@@ -50,25 +51,37 @@ exports.setLoginToken = function(token, uid, cb)
 	});
 }
 
-exports.setSessionToken = function(token, uid, cb)
+// Set session token only if empty (first login)
+// TODO: weaker security (but avoid to re-login everywhere after each logout)
+exports.trySetSessionToken = function(uid, cb)
 {
 	// Also empty the login token to invalidate future attempts
 	db.serialize(function() {
-		db.run(
-			"UPDATE Users " +
-			"SET loginToken = NULL AND sessionToken = " + token + " " +
-			"WHERE id = " + uid);
+		db.get(
+			"SELECT sessionToken " +
+			"FROM Users " +
+			"WHERE id = " + uid, (err,token) => {
+				if (!!err)
+					return cb(err);
+				const newToken = token || TokenGen.generate(params.token.length);
+				db.run(
+					"UPDATE Users " +
+					"SET loginToken = NULL " +
+					(!token ? "AND sessionToken = " + newToken + " " : "") +
+					"WHERE id = " + uid);
+				cb(null, newToken);
+		});
 	});
 }
 
-exports.updateSettings = function(name, email, notify, cb)
+exports.updateSettings = function(user, cb)
 {
 	db.serialize(function() {
 		db.run(
 			"UPDATE Users " +
-			"SET name = " + name +
-			" AND email = " + email +
-			" AND notify = " + notify + " " +
-			"WHERE id = " + uid);
+			"SET name = " + user.name +
+			" AND email = " + user.email +
+			" AND notify = " + user.notify + " " +
+			"WHERE id = " + user._id);
 	});
 }
diff --git a/routes/all.js b/routes/all.js
index 7c2a6da9..3e989f77 100644
--- a/routes/all.js
+++ b/routes/all.js
@@ -1,8 +1,11 @@
 var router = require("express").Router();
 
 router.use("/", require("./index"));
-router.use("/", require("./variant"));
+router.use("/", require("./users"));
 router.use("/", require("./problems"));
 router.use("/", require("./messages"));
+//router.use("/", require("./challenge"));
+//router.use("/", require("./playing"));
+router.use("/", require("./variant"));
 
 module.exports = router;
diff --git a/routes/users.js b/routes/users.js
index dd9914ec..297072dd 100644
--- a/routes/users.js
+++ b/routes/users.js
@@ -1,25 +1,23 @@
 var router = require("express").Router();
 var UserModel = require('../models/User');
-var maild = require('../utils/mailer');
+var sendEmail = require('../utils/mailer');
 var TokenGen = require("../utils/tokenGenerator");
 var access = require("../utils/access");
+var params = require("../config/parameters");
 
 // to: object user
 function setAndSendLoginToken(subject, to, res)
 {
 	// Set login token and send welcome(back) email with auth link
 	let token = TokenGen.generate(params.token.length);
-	UserModel.setLoginToken(token, to._id, to.ip, (err,ret) => {
+	UserModel.setLoginToken(token, to._id, (err,ret) => {
 		access.checkRequest(res, err, ret, "Cannot set login token", () => {
-			maild.send({
-				from: params.mail.from,
-				to: to.email,
-				subject: subject,
-				body: "Hello " + to.initials + "!\n" +
-					"Access your account here: " +
-					params.siteURL + "/authenticate?token=" + token + "\\n" +
-					"Token will expire in " + params.token.expire/(1000*60) + " minutes."
-			}, err => {
+			const body =
+				"Hello " + to.initials + "!\n" +
+				"Access your account here: " +
+				params.siteURL + "/authenticate?token=" + token + "\\n" +
+				"Token will expire in " + params.token.expire/(1000*60) + " minutes."
+			sendEmail(params.mail.from, to.email, subject, body, err => {
 				res.json(err || {});
 			});
 		});
@@ -36,7 +34,6 @@ router.post('/register', access.unlogged, access.ajax, (req,res) => {
 		return res.json({errmsg: error});
 	UserModel.create(name, email, (err,user) => {
 		access.checkRequest(res, err, user, "Registration failed", () => {
-			user.ip = req.ip;
 			setAndSendLoginToken("Welcome to " + params.siteURL, user, res);
 		});
 	});
@@ -45,10 +42,9 @@ router.post('/register', access.unlogged, access.ajax, (req,res) => {
 router.put('/sendtoken', access.unlogged, access.ajax, (req,res) => {
 	let email = decodeURIComponent(req.body.email);
 	let error = checkObject({email:email}, "User");
-	console.log(email)
 	if (error.length > 0)
 		return res.json({errmsg: error});
-	UserModel.getByEmail(email, (err,user) => {
+	UserModel.getOne("email", email, (err,user) => {
 		access.checkRequest(res, err, user, "Unknown user", () => {
 			setAndSendLoginToken("Token for " + params.siteURL, user, res);
 		});
@@ -58,21 +54,18 @@ router.put('/sendtoken', access.unlogged, access.ajax, (req,res) => {
 router.get('/authenticate', access.unlogged, (req,res) => {
 	UserModel.getByLoginToken(req.query.token, (err,user) => {
 		access.checkRequest(res, err, user, "Invalid token", () => {
-			if (user.loginToken.ip != req.ip)
-				return res.json({errmsg: "IP address mismatch"});
-			let now = new Date();
-			let tsNow = now.getTime();
+			let tsNow = Date.now();
 			// If token older than params.tokenExpire, do nothing
-			if (user.loginToken.timestamp + params.token.expire < tsNow)
+			if (Date.now() > user.loginTime + params.token.expire)
 				return res.json({errmsg: "Token expired"});
-			// Generate and update session token + destroy login token
-			let token = TokenGen.generate(params.token.length);
-			UserModel.setSessionToken(token, user._id, (err,ret) => {
+			// Generate session token (if not exists) + destroy login token
+			UserModel.trySetSessionToken(user._id, (err,token) => {
 				if (!!err)
 					return res.json(err);
 				// Set cookie
 				res.cookie("token", token, {
 					httpOnly: true,
+					secure: true,
 					maxAge: params.cookieExpire
 				});
 				res.redirect("/");
@@ -82,11 +75,12 @@ router.get('/authenticate', access.unlogged, (req,res) => {
 });
 
 router.put('/settings', access.logged, access.ajax, (req,res) => {
-	let user = JSON.parse(req.body.user);
-	let error = checkObject(user, "User");
-	if (error.length > 0)
-		return res.json({errmsg: error});
-	user._id = ObjectID(req.user._id);
+	const user = JSON.parse(req.body.user);
+	// TODO: either verify email + name, or re-apply the following logic:
+	//let error = checkObject(user, "User");
+	//if (error.length > 0)
+	//	return res.json({errmsg: error});
+	user._id = req.user._id; //TODO:
 	UserModel.updateSettings(user, (err,ret) => {
 		access.checkRequest(res, err, ret, "Settings update failed", () => {
 			res.json({});
@@ -94,16 +88,10 @@ router.put('/settings', access.logged, access.ajax, (req,res) => {
 	});
 });
 
+// Logout on server because the token cookie is secured + http-only
 router.get('/logout', access.logged, (req,res) => {
-	// TODO: cookie + redirect is enough (https, secure cookie
-	// https://www.information-security.fr/securite-sites-web-lutilite-flags-secure-httponly/ )
-	UserModel.logout(req.cookies.token, (err,ret) => {
-		access.checkRequest(res, err, ret, "Logout failed", () => {
-			res.clearCookie("token");
-			req.user = null;
-			res.redirect('/');
-		});
-	});
+	res.clearCookie("token");
+	res.redirect('/');
 });
 
 module.exports = router;
diff --git a/utils/mailer.js.dist b/utils/mailer.js
similarity index 76%
rename from utils/mailer.js.dist
rename to utils/mailer.js
index 06cdc591..c8080b95 100644
--- a/utils/mailer.js.dist
+++ b/utils/mailer.js
@@ -1,17 +1,16 @@
 const nodemailer = require('nodemailer');
+const params = require("../config/parameters");
 
-const contact = "your_contact_email";
-
-const send = function(from, to, subject, body, cb)
+module.exports = function(from, to, subject, body, cb)
 {
   // Create reusable transporter object using the default SMTP transport
 	const transporter = nodemailer.createTransport({
-		host: "smtp_host_address",
-		port: 465, //if secure; otherwise use 587
-		secure: true,
+		host: params.mail.host,
+		port: params.mail.port,
+		secure: params.mail.secure,
 		auth: {
-			user: "user_name",
-			pass: "user_password"
+			user: params.mail.user,
+			pass: params.mail.pass
 		}
 	});
 
@@ -42,9 +41,4 @@ const send = function(from, to, subject, body, cb)
 		//console.log('Message sent: %s', info.messageId);
 		return cb();
   });
-};
-
-module.exports = {
-	contact: contact,
-	send: send
-};
+}
diff --git a/utils/tokenGenerator.js b/utils/tokenGenerator.js
new file mode 100644
index 00000000..5578c2ec
--- /dev/null
+++ b/utils/tokenGenerator.js
@@ -0,0 +1,17 @@
+var TokenGen = {};
+
+TokenGen.rand = function()
+{
+	return Math.random().toString(36).substr(2); // remove `0.`
+};
+
+TokenGen.generate = function(tlen)
+{
+	var res = "";
+	var nbRands = Math.ceil(tlen/10); //10 = min length of a rand() string
+	for (var i = 0; i < nbRands; i++)
+		res += TokenGen.rand();
+	return res.substr(0, tlen);
+}
+
+module.exports = TokenGen;
-- 
2.44.0