User management logic half-debugged
[vchess.git] / routes / users.js
index dd9914e..f3f5199 100644 (file)
@@ -1,25 +1,24 @@
 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");
+var checkNameEmail = require("../public/javascripts/shared/userCheck")
 
 // 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.name + "!\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 || {});
                        });
                });
@@ -29,26 +28,26 @@ function setAndSendLoginToken(subject, to, res)
 // AJAX user life cycle...
 
 router.post('/register', access.unlogged, access.ajax, (req,res) => {
-       let name = decodeURIComponent(req.body.name);
-       let email = decodeURIComponent(req.body.email);
-       let error = checkObject({name:name, email:email}, "User");
-       if (error.length > 0)
+       const name = req.body.name;
+       const email = req.body.email;
+       const notify = !!req.body.notify;
+       const error = checkNameEmail({name: name, email: email});
+       if (!!error)
                return res.json({errmsg: error});
-       UserModel.create(name, email, (err,user) => {
+       UserModel.create(name, email, notify, (err,user) => {
                access.checkRequest(res, err, user, "Registration failed", () => {
-                       user.ip = req.ip;
                        setAndSendLoginToken("Welcome to " + params.siteURL, user, 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)
+router.get('/sendtoken', access.unlogged, access.ajax, (req,res) => {
+       const nameOrEmail = decodeURIComponent(req.query.nameOrEmail);
+       const type = (nameOrEmail.indexOf('@') >= 0 ? "email" : "name");
+       const error = checkNameEmail({[type]: nameOrEmail});
+       if (!!error)
                return res.json({errmsg: error});
-       UserModel.getByEmail(email, (err,user) => {
+       UserModel.getOne(type, nameOrEmail, (err,user) => {
                access.checkRequest(res, err, user, "Unknown user", () => {
                        setAndSendLoginToken("Token for " + params.siteURL, user, res);
                });
@@ -58,21 +57,17 @@ 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();
                        // 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("/");
@@ -83,10 +78,11 @@ 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)
+       const error = checkNameEmail({name: user.name, email: user.email});
+       if (!!error)
                return res.json({errmsg: error});
-       user._id = ObjectID(req.user._id);
+       user.notify = !!user.notify; //in case of...
+       user._id = res.locals.user._id; //in case of...
        UserModel.updateSettings(user, (err,ret) => {
                access.checkRequest(res, err, ret, "Settings update failed", () => {
                        res.json({});
@@ -94,16 +90,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;