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