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