ab139eb612705a663f721fb22b410285359e9f50
[vchess.git] / server / routes / users.js
1 // AJAX methods to get, create, update or delete a user
2
3 let router = require("express").Router();
4 const UserModel = require('../models/User');
5 const sendEmail = require('../utils/mailer');
6 const genToken = require("../utils/tokenGenerator");
7 const access = require("../utils/access");
8 const params = require("../config/parameters");
9
10 // NOTE: this method is safe because the sessionToken must be guessed
11 router.get("/whoami", access.ajax, (req,res) => {
12 const callback = (user) => {
13 return res.json({
14 name: user.name,
15 email: user.email,
16 id: user.id,
17 notify: user.notify,
18 });
19 };
20 const anonymous = {name:"", email:"", id:0, notify:false};
21 if (!req.cookies.token)
22 return callback(anonymous);
23 UserModel.getOne("sessionToken", req.cookies.token, function(err, user) {
24 if (!!err || !user)
25 callback(anonymous);
26 else
27 callback(user);
28 });
29 });
30
31 // NOTE: this method is safe because only IDs and names are returned
32 router.get("/users", access.ajax, (req,res) => {
33 const ids = req.query["ids"];
34 UserModel.getByIds(ids, (err,users) => {
35 if (!!err)
36 return res.json({errmsg: err.toString()});
37 return res.json({users:users});
38 });
39 });
40
41 // to: object user (to who we send an email)
42 function setAndSendLoginToken(subject, to, res)
43 {
44 // Set login token and send welcome(back) email with auth link
45 const token = genToken(params.token.length);
46 UserModel.setLoginToken(token, to.id, err => {
47 if (!!err)
48 return res.json({errmsg: err.toString()});
49 const body =
50 "Hello " + to.name + "!\\n" +
51 "Access your account here: " +
52 params.siteURL + "/#/authenticate/" + token + "\\n" +
53 "Token will expire in " + params.token.expire/(1000*60) + " minutes."
54 sendEmail(params.mail.noreply, to.email, subject, body, err => {
55 res.json(err || {});
56 });
57 });
58 }
59
60 router.post('/register', access.unlogged, access.ajax, (req,res) => {
61 const name = req.body.name;
62 const email = req.body.email;
63 const notify = !!req.body.notify;
64 const error = UserModel.checkNameEmail({name: name, email: email});
65 if (!!error)
66 return res.json({errmsg: error});
67 UserModel.create(name, email, notify, (err,uid) => {
68 if (!!err)
69 return res.json({errmsg: err.toString()});
70 const user = {
71 id: uid["rowid"],
72 name: name,
73 email: email,
74 };
75 setAndSendLoginToken("Welcome to " + params.siteURL, user, res);
76 });
77 });
78
79 router.get('/sendtoken', access.unlogged, access.ajax, (req,res) => {
80 const nameOrEmail = decodeURIComponent(req.query.nameOrEmail);
81 const type = (nameOrEmail.indexOf('@') >= 0 ? "email" : "name");
82 const error = UserModel.checkNameEmail({[type]: nameOrEmail});
83 if (!!error)
84 return res.json({errmsg: error});
85 UserModel.getOne(type, nameOrEmail, (err,user) => {
86 access.checkRequest(res, err, user, "Unknown user", () => {
87 setAndSendLoginToken("Token for " + params.siteURL, user, res);
88 });
89 });
90 });
91
92 router.get('/authenticate', access.unlogged, access.ajax, (req,res) => {
93 UserModel.getOne("loginToken", req.query.token, (err,user) => {
94 access.checkRequest(res, err, user, "Invalid token", () => {
95 // If token older than params.tokenExpire, do nothing
96 if (Date.now() > user.loginTime + params.token.expire)
97 return res.json({errmsg: "Token expired"});
98 // Generate session token (if not exists) + destroy login token
99 UserModel.trySetSessionToken(user.id, (err,token) => {
100 if (!!err)
101 return res.json({errmsg: err.toString()});
102 // Set cookie
103 res.cookie("token", token, {
104 httpOnly: true,
105 secure: !!params.siteURL.match(/^https/),
106 maxAge: params.cookieExpire,
107 });
108 res.json({
109 id: user.id,
110 name: user.name,
111 email: user.email,
112 notify: user.notify,
113 });
114 });
115 });
116 });
117 });
118
119 router.put('/update', access.logged, access.ajax, (req,res) => {
120 const name = req.body.name;
121 const email = req.body.email;
122 const error = UserModel.checkNameEmail({name: name, email: email});
123 if (!!error)
124 return res.json({errmsg: error});
125 const user = {
126 id: req.userId,
127 name: name,
128 email: email,
129 notify: !!req.body.notify,
130 };
131 UserModel.updateSettings(user, err => {
132 res.json(err ? {errmsg: err.toString()} : {});
133 });
134 });
135
136 router.get('/logout', access.logged, access.ajax, (req,res) => {
137 res.clearCookie("token");
138 res.json({});
139 });
140
141 module.exports = router;