Draft or user bio support (ready in Hall, TODO in Game)
[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 } else {
36 const user = {
37 id: ret.id,
38 name: name,
39 email: email,
40 };
41 setAndSendLoginToken("Welcome to " + params.siteURL, user, res);
42 res.json({});
43 }
44 });
45 }
46 });
47
48 // NOTE: this method is safe because the sessionToken must be guessed
49 router.get("/whoami", access.ajax, (req,res) => {
50 const callback = (user) => {
51 res.json({
52 name: user.name,
53 email: user.email,
54 id: user.id,
55 notify: user.notify
56 });
57 };
58 const anonymous = {
59 name: "",
60 email: "",
61 id: 0,
62 notify: false
63 };
64 if (!req.cookies.token) callback(anonymous);
65 else if (req.cookies.token.match(/^[a-z0-9]+$/)) {
66 UserModel.getOne("sessionToken", req.cookies.token, (err, user) => {
67 callback(user || anonymous);
68 });
69 }
70 });
71
72 // NOTE: this method is safe because only IDs and names are returned
73 router.get("/users", access.ajax, (req,res) => {
74 const ids = req.query["ids"];
75 // NOTE: slightly too permissive RegExp
76 if (ids.match(/^([0-9]+,?)+$/)) {
77 UserModel.getByIds(ids, (err, users) => {
78 res.json({ users:users });
79 });
80 }
81 });
82
83 router.put('/update', access.logged, access.ajax, (req,res) => {
84 const name = req.body.name;
85 const email = req.body.email;
86 if (UserModel.checkNameEmail({name: name, email: email})) {
87 const user = {
88 id: req.userId,
89 name: name,
90 email: email,
91 notify: !!req.body.notify,
92 };
93 UserModel.updateSettings(user);
94 res.json({});
95 }
96 });
97
98 // Authentication-related methods:
99
100 // to: object user (to who we send an email)
101 function setAndSendLoginToken(subject, to, res) {
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 UserModel.getOne(type, nameOrEmail, (err,user) => {
120 access.checkRequest(res, err, user, "Unknown user", () => {
121 setAndSendLoginToken("Token for " + params.siteURL, user, res);
122 res.json({});
123 });
124 });
125 }
126 });
127
128 router.get('/authenticate', access.unlogged, access.ajax, (req,res) => {
129 if (!req.query.token.match(/^[a-z0-9]+$/))
130 return res.json({errmsg: "Bad token"});
131 UserModel.getOne("loginToken", req.query.token, (err,user) => {
132 access.checkRequest(res, err, user, "Invalid token", () => {
133 // If token older than params.tokenExpire, do nothing
134 if (Date.now() > user.loginTime + params.token.expire)
135 res.json({errmsg: "Token expired"});
136 else {
137 // Generate session token (if not exists) + destroy login token
138 UserModel.trySetSessionToken(user.id, (token) => {
139 res.cookie("token", token, {
140 httpOnly: true,
141 secure: !!params.siteURL.match(/^https/),
142 maxAge: params.cookieExpire,
143 });
144 res.json({
145 id: user.id,
146 name: user.name,
147 email: user.email,
148 notify: user.notify,
149 });
150 });
151 }
152 });
153 });
154 });
155
156 router.get('/logout', access.logged, access.ajax, (req,res) => {
157 res.clearCookie("token");
158 res.json({});
159 });
160
161 module.exports = router;