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