Attempt to clarify installation instructions a little
[vchess.git] / server / routes / users.js
... / ...
CommitLineData
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");
7const sanitizeHtml_pkg = require('sanitize-html');
8const { exec } = require("child_process");
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}
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});
33
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;
38 if (UserModel.checkNameEmail({ name: name, email: email })) {
39 UserModel.create(name, email, notify, (err, ret) => {
40 if (!!err) {
41 const msg = err.code == "SQLITE_CONSTRAINT"
42 ? "User name or email already in use"
43 : "User creation failed. Try again";
44 res.json({ errmsg: msg });
45 }
46 else {
47 const user = {
48 id: ret.id,
49 name: name,
50 email: email
51 };
52 setAndSendLoginToken("Welcome to " + params.siteURL, user);
53 res.json({});
54 }
55 });
56 }
57});
58
59// NOTE: this method is safe because the sessionToken must be guessed
60router.get("/whoami", access.ajax, (req,res) => {
61 const callback = (user) => {
62 res.json({
63 name: user.name,
64 email: user.email,
65 id: user.id,
66 notify: user.notify
67 });
68 };
69 const anonymous = {
70 name: "",
71 email: "",
72 id: 0,
73 notify: false
74 };
75 if (!req.cookies.token) callback(anonymous);
76 else if (req.cookies.token.match(/^[a-z0-9]+$/)) {
77 UserModel.getOne(
78 "sessionToken", req.cookies.token, "name, email, id, notify",
79 (err, user) => callback(user || anonymous)
80 );
81 }
82});
83
84// NOTE: this method is safe because only IDs and names are returned
85router.get("/users", access.ajax, (req,res) => {
86 const ids = req.query["ids"];
87 // NOTE: slightly too permissive RegExp
88 if (!!ids && !!ids.match(/^([0-9]+,?)+$/)) {
89 UserModel.getByIds(ids, (err, users) => {
90 res.json({ users: users });
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;
98 if (UserModel.checkNameEmail({ name: name, email: email })) {
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 }
108});
109
110// Authentication-related methods:
111
112// to: object user (to who we send an email)
113function setAndSendLoginToken(subject, to) {
114 // Set login token and send welcome(back) email with auth link
115 const token = genToken(params.token.length);
116 UserModel.setLoginToken(token, to.id);
117 const body =
118 "Hello " + to.name + " !" + `
119` +
120 "Access your account here: " +
121 params.siteURL + "/#/authenticate/" + token + `
122` +
123 "Token will expire in " + params.token.expire/(1000*60) + " minutes."
124 sendEmail(params.mail.noreply, to.email, subject, body);
125}
126
127router.get('/sendtoken', access.unlogged, access.ajax, (req,res) => {
128 const nameOrEmail = decodeURIComponent(req.query.nameOrEmail);
129 const type = (nameOrEmail.indexOf('@') >= 0 ? "email" : "name");
130 if (UserModel.checkNameEmail({ [type]: nameOrEmail })) {
131 UserModel.getOne(type, nameOrEmail, "id, name, email", (err, user) => {
132 access.checkRequest(res, err, user, "Unknown user", () => {
133 setAndSendLoginToken("Token for " + params.siteURL, user);
134 res.json({});
135 });
136 });
137 }
138});
139
140router.get('/authenticate', access.unlogged, access.ajax, (req,res) => {
141 if (!req.query.token.match(/^[a-z0-9]+$/))
142 return res.json({ errmsg: "Bad token" });
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);
159 });
160 }
161 });
162 }
163 );
164});
165
166router.get('/logout', access.logged, access.ajax, (req,res) => {
167 res.clearCookie("token");
168 res.json({});
169});
170
171module.exports = router;