User management logic half-debugged
[vchess.git] / models / User.js
1 var db = require("../utils/database");
2 var maild = require("../utils/mailer.js");
3 var TokenGen = require("../utils/tokenGenerator");
4
5 /*
6 * Structure:
7 * _id: integer
8 * name: varchar
9 * email: varchar
10 * loginToken: token on server only
11 * loginTime: datetime (validity)
12 * sessionToken: token in cookies for authentication
13 * notify: boolean (send email notifications for corr games)
14 */
15
16 // User creation
17 exports.create = function(name, email, notify, callback)
18 {
19 db.serialize(function() {
20 const query =
21 "INSERT INTO Users " +
22 "(name, email, notify) VALUES " +
23 "('" + name + "', '" + email + "', " + notify + ")";
24 db.run(query, callback); //TODO: need to get the inserted user (how ?)
25 });
26 }
27
28 // Find one user (by id, name, email, or token)
29 exports.getOne = function(by, value, cb)
30 {
31 const delimiter = (typeof value === "string" ? "'" : "");
32 db.serialize(function() {
33 const query =
34 "SELECT * FROM Users " +
35 "WHERE " + by + " = " + delimiter + value + delimiter;
36 db.get(query, cb);
37 });
38 }
39
40 /////////
41 // MODIFY
42
43 exports.setLoginToken = function(token, uid, cb)
44 {
45 db.serialize(function() {
46 const query =
47 "UPDATE Users " +
48 "SET loginToken = " + token + " AND loginTime = " + Date.now() + " " +
49 "WHERE id = " + uid;
50 db.run(query, cb);
51 });
52 }
53
54 // Set session token only if empty (first login)
55 // TODO: weaker security (but avoid to re-login everywhere after each logout)
56 exports.trySetSessionToken = function(uid, cb)
57 {
58 // Also empty the login token to invalidate future attempts
59 db.serialize(function() {
60 const querySessionTOken =
61 "SELECT sessionToken " +
62 "FROM Users " +
63 "WHERE id = " + uid;
64 db.get(querySessionToken, (err,token) => {
65 if (!!err)
66 return cb(err);
67 const newToken = token || TokenGen.generate(params.token.length);
68 const queryUpdate =
69 "UPDATE Users " +
70 "SET loginToken = NULL " +
71 (!token ? "AND sessionToken = " + newToken + " " : "") +
72 "WHERE id = " + uid;
73 db.run(queryUpdate);
74 cb(null, newToken);
75 });
76 });
77 }
78
79 exports.updateSettings = function(user, cb)
80 {
81 db.serialize(function() {
82 const query =
83 "UPDATE Users " +
84 "SET name = " + user.name +
85 " AND email = " + user.email +
86 " AND notify = " + user.notify + " " +
87 "WHERE id = " + user._id;
88 db.run(query, cb);
89 });
90 }