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