Better board size auto-adjust. Still far from perfect
[vchess.git] / server / routes / users.js
CommitLineData
fe4c7e67
BA
1let router = require("express").Router();
2const UserModel = require('../models/User');
3const sendEmail = require('../utils/mailer');
4const genToken = require("../utils/tokenGenerator");
5const access = require("../utils/access");
6const params = require("../config/parameters");
ad65975c 7const sanitizeHtml_pkg = require('sanitize-html');
0aa79c55 8const { exec } = require("child_process");
ad65975c
BA
9
10const allowedTags = [
11 'h3', 'h4', 'h5', 'h6', 'blockquote', 'p', 'a', 'ul', 'ol', 'li', 'b',
12 'i', 'strong', 'em', 'strike', 'code', 'hr', 'br', 'div', 'table',
13 'thead', 'caption', 'tbody', 'tr', 'th', 'td', 'pre'
14];
15function sanitizeHtml(text) {
16 return sanitizeHtml_pkg(text, { allowedTags: allowedTags });
17}
dd10eb93
BA
18
19router.get("/userbio", access.ajax, (req,res) => {
20 const uid = req.query["id"];
21 if (!!(uid.toString().match(/^[0-9]+$/))) {
22 UserModel.getBio(uid, (err, bio) => {
23 res.json(bio);
24 });
25 }
26});
27
28router.put('/userbio', access.logged, access.ajax, (req,res) => {
29 const bio = sanitizeHtml(req.body.bio);
30 UserModel.setBio(req.userId, bio);
31 res.json({});
32});
8d7e2786 33
866842c3
BA
34router.post('/register', access.unlogged, access.ajax, (req,res) => {
35 const name = req.body.name;
36 const email = req.body.email;
37 const notify = !!req.body.notify;
58aedcd1 38 if (UserModel.checkNameEmail({ name: name, email: email })) {
0234201f
BA
39 UserModel.create(name, email, notify, (err, ret) => {
40 if (!!err) {
f0c68a04
BA
41 const msg = err.code == "SQLITE_CONSTRAINT"
42 ? "User name or email already in use"
43 : "User creation failed. Try again";
58aedcd1 44 res.json({ errmsg: msg });
80b38d46
BA
45 }
46 else {
866842c3 47 const user = {
0234201f 48 id: ret.id,
866842c3 49 name: name,
58aedcd1 50 email: email
866842c3 51 };
d9845792 52 setAndSendLoginToken("Welcome to " + params.siteURL, user);
0aa79c55 53 // Update tournament DB (TODO: if error, log it)
c3949cbd 54 exec(params.tourneyPath + "/dbsync/insert_user.py " + ret.id);
866842c3
BA
55 res.json({});
56 }
57 });
58 }
59});
60
58e7b94e 61// NOTE: this method is safe because the sessionToken must be guessed
e57c4de4 62router.get("/whoami", access.ajax, (req,res) => {
a7f9f050 63 const callback = (user) => {
866842c3 64 res.json({
a7f9f050
BA
65 name: user.name,
66 email: user.email,
67 id: user.id,
dd10eb93 68 notify: user.notify
a7f9f050
BA
69 });
70 };
5c026d9a
BA
71 const anonymous = {
72 name: "",
73 email: "",
74 id: 0,
dd10eb93 75 notify: false
5c026d9a 76 };
0234201f
BA
77 if (!req.cookies.token) callback(anonymous);
78 else if (req.cookies.token.match(/^[a-z0-9]+$/)) {
fccaa878
BA
79 UserModel.getOne(
80 "sessionToken", req.cookies.token, "name, email, id, notify",
81 (err, user) => callback(user || anonymous)
82 );
866842c3 83 }
a7f9f050
BA
84});
85
58e7b94e 86// NOTE: this method is safe because only IDs and names are returned
bebcc8d4 87router.get("/users", access.ajax, (req,res) => {
ed9c9c37 88 const ids = req.query["ids"];
0234201f 89 // NOTE: slightly too permissive RegExp
d639b82a 90 if (!!ids && !!ids.match(/^([0-9]+,?)+$/)) {
dd10eb93 91 UserModel.getByIds(ids, (err, users) => {
58aedcd1 92 res.json({ users: users });
866842c3
BA
93 });
94 }
95});
96
97router.put('/update', access.logged, access.ajax, (req,res) => {
98 const name = req.body.name;
99 const email = req.body.email;
58aedcd1 100 if (UserModel.checkNameEmail({ name: name, email: email })) {
866842c3
BA
101 const user = {
102 id: req.userId,
103 name: name,
104 email: email,
105 notify: !!req.body.notify,
106 };
107 UserModel.updateSettings(user);
c3949cbd 108 exec(params.tourneyPath + "/dbsync/update_user.py " + ret.id);
866842c3
BA
109 res.json({});
110 }
bebcc8d4
BA
111});
112
866842c3
BA
113// Authentication-related methods:
114
c018b304 115// to: object user (to who we send an email)
d9845792 116function setAndSendLoginToken(subject, to) {
dac39588
BA
117 // Set login token and send welcome(back) email with auth link
118 const token = genToken(params.token.length);
866842c3
BA
119 UserModel.setLoginToken(token, to.id);
120 const body =
f53871db 121 "Hello " + to.name + " !" + `
a749972c 122` +
866842c3
BA
123 "Access your account here: " +
124 params.siteURL + "/#/authenticate/" + token + `
a749972c 125` +
866842c3
BA
126 "Token will expire in " + params.token.expire/(1000*60) + " minutes."
127 sendEmail(params.mail.noreply, to.email, subject, body);
8d7e2786
BA
128}
129
8a477a7e 130router.get('/sendtoken', access.unlogged, access.ajax, (req,res) => {
dac39588
BA
131 const nameOrEmail = decodeURIComponent(req.query.nameOrEmail);
132 const type = (nameOrEmail.indexOf('@') >= 0 ? "email" : "name");
58aedcd1 133 if (UserModel.checkNameEmail({ [type]: nameOrEmail })) {
fccaa878 134 UserModel.getOne(type, nameOrEmail, "id, name, email", (err, user) => {
866842c3 135 access.checkRequest(res, err, user, "Unknown user", () => {
d9845792 136 setAndSendLoginToken("Token for " + params.siteURL, user);
866842c3
BA
137 res.json({});
138 });
dac39588 139 });
866842c3 140 }
8d7e2786
BA
141});
142
1aeed627 143router.get('/authenticate', access.unlogged, access.ajax, (req,res) => {
99b7a14c 144 if (!req.query.token.match(/^[a-z0-9]+$/))
58aedcd1 145 return res.json({ errmsg: "Bad token" });
fccaa878
BA
146 UserModel.getOne(
147 "loginToken", req.query.token, "id, name, email, notify",
148 (err,user) => {
149 access.checkRequest(res, err, user, "Invalid token", () => {
150 // If token older than params.tokenExpire, do nothing
151 if (Date.now() > user.loginTime + params.token.expire)
152 res.json({ errmsg: "Token expired" });
153 else {
154 // Generate session token (if not exists) + destroy login token
155 UserModel.trySetSessionToken(user.id, (token) => {
156 res.cookie("token", token, {
157 httpOnly: true,
158 secure: !!params.siteURL.match(/^https/),
159 maxAge: params.cookieExpire,
160 });
161 res.json(user);
866842c3 162 });
fccaa878
BA
163 }
164 });
165 }
166 );
8d7e2786
BA
167});
168
1aeed627 169router.get('/logout', access.logged, access.ajax, (req,res) => {
dac39588
BA
170 res.clearCookie("token");
171 res.json({});
8d7e2786
BA
172});
173
174module.exports = router;