Attempt to clarify installation instructions a little
[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);
866842c3
BA
53 res.json({});
54 }
55 });
56 }
57});
58
58e7b94e 59// NOTE: this method is safe because the sessionToken must be guessed
e57c4de4 60router.get("/whoami", access.ajax, (req,res) => {
a7f9f050 61 const callback = (user) => {
866842c3 62 res.json({
a7f9f050
BA
63 name: user.name,
64 email: user.email,
65 id: user.id,
dd10eb93 66 notify: user.notify
a7f9f050
BA
67 });
68 };
5c026d9a
BA
69 const anonymous = {
70 name: "",
71 email: "",
72 id: 0,
dd10eb93 73 notify: false
5c026d9a 74 };
0234201f
BA
75 if (!req.cookies.token) callback(anonymous);
76 else if (req.cookies.token.match(/^[a-z0-9]+$/)) {
fccaa878
BA
77 UserModel.getOne(
78 "sessionToken", req.cookies.token, "name, email, id, notify",
79 (err, user) => callback(user || anonymous)
80 );
866842c3 81 }
a7f9f050
BA
82});
83
58e7b94e 84// NOTE: this method is safe because only IDs and names are returned
bebcc8d4 85router.get("/users", access.ajax, (req,res) => {
ed9c9c37 86 const ids = req.query["ids"];
0234201f 87 // NOTE: slightly too permissive RegExp
d639b82a 88 if (!!ids && !!ids.match(/^([0-9]+,?)+$/)) {
dd10eb93 89 UserModel.getByIds(ids, (err, users) => {
58aedcd1 90 res.json({ users: users });
866842c3
BA
91 });
92 }
93});
94
95router.put('/update', access.logged, access.ajax, (req,res) => {
96 const name = req.body.name;
97 const email = req.body.email;
58aedcd1 98 if (UserModel.checkNameEmail({ name: name, email: email })) {
866842c3
BA
99 const user = {
100 id: req.userId,
101 name: name,
102 email: email,
103 notify: !!req.body.notify,
104 };
105 UserModel.updateSettings(user);
106 res.json({});
107 }
bebcc8d4
BA
108});
109
866842c3
BA
110// Authentication-related methods:
111
c018b304 112// to: object user (to who we send an email)
d9845792 113function setAndSendLoginToken(subject, to) {
dac39588
BA
114 // Set login token and send welcome(back) email with auth link
115 const token = genToken(params.token.length);
866842c3
BA
116 UserModel.setLoginToken(token, to.id);
117 const body =
f53871db 118 "Hello " + to.name + " !" + `
a749972c 119` +
866842c3
BA
120 "Access your account here: " +
121 params.siteURL + "/#/authenticate/" + token + `
a749972c 122` +
866842c3
BA
123 "Token will expire in " + params.token.expire/(1000*60) + " minutes."
124 sendEmail(params.mail.noreply, to.email, subject, body);
8d7e2786
BA
125}
126
8a477a7e 127router.get('/sendtoken', access.unlogged, access.ajax, (req,res) => {
dac39588
BA
128 const nameOrEmail = decodeURIComponent(req.query.nameOrEmail);
129 const type = (nameOrEmail.indexOf('@') >= 0 ? "email" : "name");
58aedcd1 130 if (UserModel.checkNameEmail({ [type]: nameOrEmail })) {
fccaa878 131 UserModel.getOne(type, nameOrEmail, "id, name, email", (err, user) => {
866842c3 132 access.checkRequest(res, err, user, "Unknown user", () => {
d9845792 133 setAndSendLoginToken("Token for " + params.siteURL, user);
866842c3
BA
134 res.json({});
135 });
dac39588 136 });
866842c3 137 }
8d7e2786
BA
138});
139
1aeed627 140router.get('/authenticate', access.unlogged, access.ajax, (req,res) => {
99b7a14c 141 if (!req.query.token.match(/^[a-z0-9]+$/))
58aedcd1 142 return res.json({ errmsg: "Bad token" });
fccaa878
BA
143 UserModel.getOne(
144 "loginToken", req.query.token, "id, name, email, notify",
145 (err,user) => {
146 access.checkRequest(res, err, user, "Invalid token", () => {
147 // If token older than params.tokenExpire, do nothing
148 if (Date.now() > user.loginTime + params.token.expire)
149 res.json({ errmsg: "Token expired" });
150 else {
151 // Generate session token (if not exists) + destroy login token
152 UserModel.trySetSessionToken(user.id, (token) => {
153 res.cookie("token", token, {
154 httpOnly: true,
155 secure: !!params.siteURL.match(/^https/),
156 maxAge: params.cookieExpire,
157 });
158 res.json(user);
866842c3 159 });
fccaa878
BA
160 }
161 });
162 }
163 );
8d7e2786
BA
164});
165
1aeed627 166router.get('/logout', access.logged, access.ajax, (req,res) => {
dac39588
BA
167 res.clearCookie("token");
168 res.json({});
8d7e2786
BA
169});
170
171module.exports = router;