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