Experimental multi-tabs support (TODO: prevent multi-connect)
[vchess.git] / server / routes / users.js
CommitLineData
582df349
BA
1// AJAX methods to get, create, update or delete a user
2
fe4c7e67
BA
3let router = require("express").Router();
4const UserModel = require('../models/User');
5const sendEmail = require('../utils/mailer');
6const genToken = require("../utils/tokenGenerator");
7const access = require("../utils/access");
8const params = require("../config/parameters");
8d7e2786 9
58e7b94e 10// NOTE: this method is safe because the sessionToken must be guessed
a7f9f050
BA
11router.get("/whoami", access.ajax, (req,res) => {
12 const callback = (user) => {
13 return res.json({
14 name: user.name,
15 email: user.email,
16 id: user.id,
17 notify: user.notify,
18 });
19 };
20 const anonymous = {name:"", email:"", id:0, notify:false};
dac39588 21 if (!req.cookies.token)
a7f9f050 22 return callback(anonymous);
99b7a14c
BA
23 if (!req.cookies.token.match(/^[a-z0-9]+$/))
24 return res.json({errmsg: "Bad token"});
a7f9f050
BA
25 UserModel.getOne("sessionToken", req.cookies.token, function(err, user) {
26 if (!!err || !user)
27 callback(anonymous);
f21cd6d9 28 else
a7f9f050
BA
29 callback(user);
30 });
31});
32
58e7b94e 33// NOTE: this method is safe because only IDs and names are returned
bebcc8d4 34router.get("/users", access.ajax, (req,res) => {
ed9c9c37 35 const ids = req.query["ids"];
fcbc92c2 36 if (!!ids && !ids.match(/^([0-9]+,?)+$/)) //NOTE: slightly too permissive
99b7a14c 37 return res.json({errmsg: "Bad IDs array"});
ed9c9c37
BA
38 UserModel.getByIds(ids, (err,users) => {
39 if (!!err)
40 return res.json({errmsg: err.toString()});
41 return res.json({users:users});
42 });
bebcc8d4
BA
43});
44
c018b304 45// to: object user (to who we send an email)
8d7e2786
BA
46function setAndSendLoginToken(subject, to, res)
47{
dac39588
BA
48 // Set login token and send welcome(back) email with auth link
49 const token = genToken(params.token.length);
50 UserModel.setLoginToken(token, to.id, err => {
51 if (!!err)
52 return res.json({errmsg: err.toString()});
53 const body =
37ac10c2 54 "Hello " + to.name + "!" + `
a749972c 55` +
dac39588 56 "Access your account here: " +
37ac10c2 57 params.siteURL + "/#/authenticate/" + token + `
a749972c 58` +
dac39588
BA
59 "Token will expire in " + params.token.expire/(1000*60) + " minutes."
60 sendEmail(params.mail.noreply, to.email, subject, body, err => {
61 res.json(err || {});
62 });
63 });
8d7e2786
BA
64}
65
8d7e2786 66router.post('/register', access.unlogged, access.ajax, (req,res) => {
dac39588
BA
67 const name = req.body.name;
68 const email = req.body.email;
69 const notify = !!req.body.notify;
70 const error = UserModel.checkNameEmail({name: name, email: email});
71 if (!!error)
72 return res.json({errmsg: error});
73 UserModel.create(name, email, notify, (err,uid) => {
74 if (!!err)
75 return res.json({errmsg: err.toString()});
76 const user = {
77 id: uid["rowid"],
78 name: name,
79 email: email,
80 };
81 setAndSendLoginToken("Welcome to " + params.siteURL, user, res);
82 });
8d7e2786
BA
83});
84
8a477a7e 85router.get('/sendtoken', access.unlogged, access.ajax, (req,res) => {
dac39588
BA
86 const nameOrEmail = decodeURIComponent(req.query.nameOrEmail);
87 const type = (nameOrEmail.indexOf('@') >= 0 ? "email" : "name");
88 const error = UserModel.checkNameEmail({[type]: nameOrEmail});
89 if (!!error)
90 return res.json({errmsg: error});
91 UserModel.getOne(type, nameOrEmail, (err,user) => {
92 access.checkRequest(res, err, user, "Unknown user", () => {
93 setAndSendLoginToken("Token for " + params.siteURL, user, res);
94 });
95 });
8d7e2786
BA
96});
97
1aeed627 98router.get('/authenticate', access.unlogged, access.ajax, (req,res) => {
99b7a14c
BA
99 if (!req.query.token.match(/^[a-z0-9]+$/))
100 return res.json({errmsg: "Bad token"});
1aeed627 101 UserModel.getOne("loginToken", req.query.token, (err,user) => {
dac39588 102 access.checkRequest(res, err, user, "Invalid token", () => {
98f48579 103 // If token older than params.tokenExpire, do nothing
dac39588
BA
104 if (Date.now() > user.loginTime + params.token.expire)
105 return res.json({errmsg: "Token expired"});
106 // Generate session token (if not exists) + destroy login token
107 UserModel.trySetSessionToken(user.id, (err,token) => {
108 if (!!err)
109 return res.json({errmsg: err.toString()});
110 // Set cookie
a7f9f050 111 res.cookie("token", token, {
dac39588
BA
112 httpOnly: true,
113 secure: !!params.siteURL.match(/^https/),
114 maxAge: params.cookieExpire,
115 });
116 res.json({
a7f9f050
BA
117 id: user.id,
118 name: user.name,
119 email: user.email,
120 notify: user.notify,
121 });
dac39588
BA
122 });
123 });
124 });
8d7e2786
BA
125});
126
c018b304 127router.put('/update', access.logged, access.ajax, (req,res) => {
dac39588
BA
128 const name = req.body.name;
129 const email = req.body.email;
130 const error = UserModel.checkNameEmail({name: name, email: email});
131 if (!!error)
132 return res.json({errmsg: error});
133 const user = {
134 id: req.userId,
135 name: name,
136 email: email,
137 notify: !!req.body.notify,
138 };
139 UserModel.updateSettings(user, err => {
140 res.json(err ? {errmsg: err.toString()} : {});
141 });
8d7e2786
BA
142});
143
1aeed627 144router.get('/logout', access.logged, access.ajax, (req,res) => {
dac39588
BA
145 res.clearCookie("token");
146 res.json({});
8d7e2786
BA
147});
148
149module.exports = router;