1 var db
= require("../utils/database");
2 var genToken
= require("../utils/tokenGenerator");
3 var params
= require("../config/parameters");
4 var sendEmail
= require('../utils/mailer');
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)
19 checkNameEmail: function(o
)
21 if (typeof o
.name
=== "string")
23 if (o
.name
.length
== 0)
25 if (!o
.name
.match(/^[\w]+$/))
26 return "Bad characters in name";
28 if (typeof o
.email
=== "string")
30 if (o
.email
.length
== 0)
32 if (!o
.email
.match(/^[\w.+-]+@[\w.+-]+$/))
33 return "Bad characters in email";
37 // NOTE: parameters are already cleaned (in controller), thus no sanitization here
38 create: function(name
, email
, notify
, callback
)
40 db
.serialize(function() {
42 "INSERT INTO Users " +
43 "(name, email, notify) VALUES " +
44 "('" + name
+ "', '" + email
+ "', " + notify
+ ")";
45 db
.run(insertQuery
, err
=> {
48 db
.get("SELECT last_insert_rowid() AS rowid", callback
);
53 // Find one user (by id, name, email, or token)
54 getOne: function(by
, value
, cb
)
56 const delimiter
= (typeof value
=== "string" ? "'" : "");
57 db
.serialize(function() {
61 "WHERE " + by
+ " = " + delimiter
+ value
+ delimiter
;
66 getByIds: function(ids
, cb
) {
67 db
.serialize(function() {
71 "WHERE id IN (" + ids
+ ")";
79 setLoginToken: function(token
, uid
, cb
)
81 db
.serialize(function() {
84 "SET loginToken = '" + token
+ "', loginTime = " + Date
.now() + " " +
90 // Set session token only if empty (first login)
91 // TODO: weaker security (but avoid to re-login everywhere after each logout)
92 trySetSessionToken: function(uid
, cb
)
94 // Also empty the login token to invalidate future attempts
95 db
.serialize(function() {
96 const querySessionToken
=
97 "SELECT sessionToken " +
100 db
.get(querySessionToken
, (err
,ret
) => {
103 const token
= ret
.sessionToken
|| genToken(params
.token
.length
);
106 "SET loginToken = NULL" +
107 (!ret
.sessionToken
? (", sessionToken = '" + token
+ "'") : "") + " " +
115 updateSettings: function(user
, cb
)
117 db
.serialize(function() {
120 "SET name = '" + user
.name
+ "'" +
121 ", email = '" + user
.email
+ "'" +
122 ", notify = " + user
.notify
+ " " +
123 "WHERE id = " + user
.id
;
131 tryNotify: function(oppId
, message
)
133 UserModel
.getOne("id", oppId
, (err
,opp
) => {
134 if (!err
|| !opp
.notify
)
135 return; //error is ignored here (TODO: should be logged)
136 const subject
= "vchess.club - notification";
137 const body
= "Hello " + opp
.name
+ "!\n" + message
;
138 sendEmail(params
.mail
.noreply
, opp
.email
, subject
, body
, err
=> {
145 module
.exports
= UserModel
;