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