var db = require("../utils/database");
-var maild = require("../utils/mailer.js");
var genToken = require("../utils/tokenGenerator");
var params = require("../config/parameters");
+var sendEmail = require('../utils/mailer');
/*
* Structure:
* loginTime: datetime (validity)
* sessionToken: token in cookies for authentication
* notify: boolean (send email notifications for corr games)
+ * created: datetime
*/
const UserModel =
if (!o.email.match(/^[\w.+-]+@[\w.+-]+$/))
return "Bad characters in email";
}
+ return ""; //NOTE: not required, but more consistent... (?!)
},
// NOTE: parameters are already cleaned (in controller), thus no sanitization here
db.serialize(function() {
const insertQuery =
"INSERT INTO Users " +
- "(name, email, notify) VALUES " +
- "('" + name + "', '" + email + "', " + notify + ")";
+ "(name, email, notify, created) VALUES " +
+ "('" + name + "', '" + email + "', " + notify + "," + Date.now() + ")";
db.run(insertQuery, err => {
if (!!err)
return callback(err);
});
},
- getByName: function(names, cb) {
- db.serialize(function() {
- const query =
- "SELECT id " +
+ getByIds: function(ids, cb) {
+ db.serialize(function() {
+ const query =
+ "SELECT id, name " +
"FROM Users " +
- "WHERE name IN ('" + names.join("','") + "')";
- db.all(query, cb);
- });
+ "WHERE id IN (" + ids + ")";
+ db.all(query, cb);
+ });
},
/////////
},
// Set session token only if empty (first login)
- // TODO: weaker security (but avoid to re-login everywhere after each logout)
- trySetSessionToken: function(uid, cb)
+ // NOTE: weaker security (but avoid to re-login everywhere after each logout)
+ // TODO: option would be to reset all tokens periodically, e.g. every 3 months
+ trySetSessionToken: function(uid, cb)
{
// Also empty the login token to invalidate future attempts
db.serialize(function() {
db.run(query, cb);
});
},
+
+ /////////////////
+ // NOTIFICATIONS
+
+ tryNotify: function(oppId, message)
+ {
+ UserModel.getOne("id", oppId, (err,opp) => {
+ if (!err || !opp.notify)
+ return; //error is ignored here (TODO: should be logged)
+ const subject = "vchess.club - notification";
+ const body = "Hello " + opp.name + "!\n" + message;
+ sendEmail(params.mail.noreply, opp.email, subject, body, err => {
+ res.json(err || {});
+ });
+ });
+ },
+
+ ////////////
+ // CLEANING
+
+ cleanUsersDb: function()
+ {
+ const tsNow = Date.now();
+ // 86400000 = 24 hours in milliseconds
+ const day = 86400000;
+ db.serialize(function() {
+ const query =
+ "SELECT id, sessionToken, created " +
+ "FROM Users";
+ db.all(query, (err, users) => {
+ users.forEach(u => {
+ // Remove unlogged users for >1 day
+ if (!u.sessionToken && tsNow - u.created > day)
+ db.run("DELETE FROM Users WHERE id = " + u.id);
+ });
+ });
+ });
+ },
}
module.exports = UserModel;