Advance on users management. TODO: routes/users + debug + test
[vchess.git] / models / User.js
CommitLineData
8d7e2786
BA
1var db = require("../utils/database");
2var maild = require("../utils/mailer.js");
3
4/*
5 * Structure:
6 * _id: integer
7 * name: varchar
8 * email: varchar
9 * loginToken: token on server only
10 * loginTime: datetime (validity)
11 * sessionToken: token in cookies for authentication
12 * notify: boolean (send email notifications for corr games)
13 */
14
15// User creation
16exports.create = function(name, email, notify, callback)
17{
18 if (!notify)
19 notify = false; //default
20 db.serialize(function() {
21 db.run(
22 "INSERT INTO Users " +
23 "(name, email, notify) VALUES " +
24 "(" + name + "," + email + "," + notify + ")");
25 });
26}
27
28// Find one user (by id, name, email, or token)
29exports.getOne = function(by, value, cb)
30{
31 const delimiter = (typeof value === "string" ? "'" : "");
32 db.serialize(function() {
33 db.get(
34 "SELECT * FROM Users " +
35 "WHERE " + by " = " + delimiter + value + delimiter,
36 callback);
37 });
38}
39
40/////////
41// MODIFY
42
43exports.setLoginToken = function(token, uid, cb)
44{
45 db.serialize(function() {
46 db.run(
47 "UPDATE Users " +
48 "SET loginToken = " + token + " AND loginTime = " + Date.now() + " " +
49 "WHERE id = " + uid);
50 });
51}
52
53exports.setSessionToken = function(token, uid, cb)
54{
55 // Also empty the login token to invalidate future attempts
56 db.serialize(function() {
57 db.run(
58 "UPDATE Users " +
59 "SET loginToken = NULL AND sessionToken = " + token + " " +
60 "WHERE id = " + uid);
61 });
62}
63
64exports.updateSettings = function(name, email, notify, cb)
65{
66 db.serialize(function() {
67 db.run(
68 "UPDATE Users " +
69 "SET name = " + name +
70 " AND email = " + email +
71 " AND notify = " + notify + " " +
72 "WHERE id = " + uid);
73 });
74}