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