Skip to content

Commit

Permalink
Implement self-service account deletion
Browse files Browse the repository at this point in the history
  • Loading branch information
calzoneman committed Dec 8, 2018
1 parent 37c6fa3 commit aa23486
Show file tree
Hide file tree
Showing 13 changed files with 426 additions and 19 deletions.
25 changes: 25 additions & 0 deletions conf/example/email.toml
Expand Up @@ -39,3 +39,28 @@ This email address is not monitored for replies. For assistance with password r

from = "Example Website <website@example.com>"
subject = "Password reset request"

# Email configuration for account deletion request notifications
[delete-account]
enabled = true

html-template = """
Hi $user$,
<br>
<br>
Account deletion was requested for your account on CHANGE ME. Your account will be automatically deleted in 7 days without any further action from you.
<br>
<br>
This email address is not monitored for replies. For assistance, please <a href="http://example.com/contact">contact an administrator</a>.
"""

text-template = """
Hi $user$,
Account deletion was requested for your account on CHANGE ME. Your account will be automatically deleted in 7 days without any further action from you.
This email address is not monitored for replies. For assistance, please contact an administrator. See http://example.com/contact for contact information.
"""

from = "Example Website <website@example.com>"
subject = "Account deletion request"
28 changes: 24 additions & 4 deletions src/bgtask.js
Expand Up @@ -14,7 +14,7 @@ const LOGGER = require('@calzoneman/jsli')('bgtask');
var init = null;

/* Alias cleanup */
function initAliasCleanup(_Server) {
function initAliasCleanup() {
var CLEAN_INTERVAL = parseInt(Config.get("aliases.purge-interval"));
var CLEAN_EXPIRE = parseInt(Config.get("aliases.max-age"));

Expand All @@ -28,7 +28,7 @@ function initAliasCleanup(_Server) {
}

/* Password reset cleanup */
function initPasswordResetCleanup(_Server) {
function initPasswordResetCleanup() {
var CLEAN_INTERVAL = 8*60*60*1000;

setInterval(function () {
Expand Down Expand Up @@ -74,14 +74,34 @@ function initChannelDumper(Server) {
}, CHANNEL_SAVE_INTERVAL);
}

function initAccountCleanup() {
setInterval(() => {
(async () => {
let rows = await db.users.findAccountsPendingDeletion();
for (let row of rows) {
try {
await db.users.purgeAccount(row.id);
LOGGER.info('Purged account from request %j', row);
} catch (error) {
LOGGER.error('Error purging account %j: %s', row, error.stack);
}
}
})().catch(error => {
LOGGER.error('Error purging deleted accounts: %s', error.stack);
});
//}, 3600 * 1000);
}, 60 * 1000);
}

module.exports = function (Server) {
if (init === Server) {
LOGGER.warn("Attempted to re-init background tasks");
return;
}

init = Server;
initAliasCleanup(Server);
initAliasCleanup();
initChannelDumper(Server);
initPasswordResetCleanup(Server);
initPasswordResetCleanup();
initAccountCleanup();
};
27 changes: 27 additions & 0 deletions src/configuration/emailconfig.js
Expand Up @@ -47,6 +47,29 @@ class EmailConfig {
return reset.subject;
}
};

const deleteAccount = config['delete-account'];
this._delete = {
isEnabled() {
return deleteAccount !== null && deleteAccount.enabled;
},

getHTML() {
return deleteAccount['html-template'];
},

getText() {
return deleteAccount['text-template'];
},

getFrom() {
return deleteAccount.from;
},

getSubject() {
return deleteAccount.subject;
}
};
}

getSmtp() {
Expand All @@ -56,6 +79,10 @@ class EmailConfig {
getPasswordReset() {
return this._reset;
}

getDeleteAccount() {
return this._delete;
}
}

export { EmailConfig };
21 changes: 21 additions & 0 deletions src/controller/email.js
Expand Up @@ -26,6 +26,27 @@ class EmailController {

return result;
}

async sendAccountDeletion(params = {}) {
const { address, username } = params;

const deleteConfig = this.config.getDeleteAccount();

const html = deleteConfig.getHTML()
.replace(/\$user\$/g, username);
const text = deleteConfig.getText()
.replace(/\$user\$/g, username);

const result = await this.mailer.sendMail({
from: deleteConfig.getFrom(),
to: `${username} <${address}>`,
subject: deleteConfig.getSubject(),
html,
text
});

return result;
}
}

export { EmailController };
72 changes: 58 additions & 14 deletions src/database/accounts.js
Expand Up @@ -2,6 +2,7 @@ var $util = require("../utilities");
var bcrypt = require("bcrypt");
var db = require("../database");
var Config = require("../config");
import { promisify } from "bluebird";

const LOGGER = require('@calzoneman/jsli')('database/accounts');

Expand Down Expand Up @@ -89,7 +90,9 @@ module.exports = {
return;
}

db.query("SELECT * FROM `users` WHERE name = ?", [name], function (err, rows) {
db.query("SELECT * FROM `users` WHERE name = ? AND inactive = FALSE",
[name],
function (err, rows) {
if (err) {
callback(err, true);
return;
Expand Down Expand Up @@ -244,7 +247,7 @@ module.exports = {
the hashes match.
*/

db.query("SELECT * FROM `users` WHERE name=?",
db.query("SELECT * FROM `users` WHERE name=? AND inactive = FALSE",
[name],
function (err, rows) {
if (err) {
Expand Down Expand Up @@ -401,7 +404,7 @@ module.exports = {
return;
}

db.query("SELECT email FROM `users` WHERE name=?", [name],
db.query("SELECT email FROM `users` WHERE name=? AND inactive = FALSE", [name],
function (err, rows) {
if (err) {
callback(err, null);
Expand Down Expand Up @@ -519,17 +522,6 @@ module.exports = {
});
},

/**
* Retrieve a list of channels owned by a user
*/
getChannels: function (name, callback) {
if (typeof callback !== "function") {
return;
}

db.query("SELECT * FROM `channels` WHERE owner=?", [name], callback);
},

/**
* Retrieves all names registered from a given IP
*/
Expand All @@ -540,5 +532,57 @@ module.exports = {

db.query("SELECT name,global_rank FROM `users` WHERE `ip`=?", [ip],
callback);
},

requestAccountDeletion: id => {
return db.getDB().runTransaction(async tx => {
try {
let user = await tx.table('users').where({ id }).first();
await tx.table('user_deletion_requests')
.insert({
user_id: id
});
await tx.table('users')
.where({ id })
.update({ password: '', inactive: true });

// TODO: ideally password reset should be by user_id and not name
// For now, we need to make sure to clear it
await tx.table('password_reset')
.where({ name: user.name })
.delete();
} catch (error) {
// Ignore unique violation -- probably caused by a duplicate request
if (error.code !== 'ER_DUP_ENTRY') {
throw error;
}
}
});
},

findAccountsPendingDeletion: () => {
return db.getDB().runTransaction(tx => {
let lastWeek = new Date(Date.now() - 7 * 24 * 3600 * 1000);
return tx.table('user_deletion_requests')
.where('user_deletion_requests.created_at', '<', lastWeek)
.join('users', 'user_deletion_requests.user_id', '=', 'users.id')
.select('users.id', 'users.name');
});
},

purgeAccount: id => {
return db.getDB().runTransaction(async tx => {
let user = await tx.table('users').where({ id }).first();
if (!user) {
return false;
}

await tx.table('channel_ranks').where({ name: user.name }).delete();
await tx.table('user_playlists').where({ user: user.name }).delete();
await tx.table('users').where({ id }).delete();
return true;
});
}
};

module.exports.verifyLoginAsync = promisify(module.exports.verifyLogin);
12 changes: 12 additions & 0 deletions src/database/channels.js
Expand Up @@ -230,6 +230,18 @@ module.exports = {
});
},

listUserChannelsAsync: owner => {
return new Promise((resolve, reject) => {
module.exports.listUserChannels(owner, (error, rows) => {
if (error) {
reject(error);
} else {
resolve(rows);
}
});
});
},

/**
* Loads the channel from the database
*/
Expand Down
12 changes: 12 additions & 0 deletions src/database/tables.js
Expand Up @@ -129,4 +129,16 @@ export async function initTables() {
t.index(['ip', 'channel']);
t.index(['name', 'channel']);
});

await ensureTable('user_deletion_requests', t => {
t.increments('request_id').notNullable().primary();
t.integer('user_id')
.unsigned()
.notNullable()
.references('id').inTable('users')
.onDelete('cascade')
.unique();
t.timestamps(/* useTimestamps */ true, /* defaultToNow */ true);
t.index('created_at');
});
}
15 changes: 14 additions & 1 deletion src/database/update.js
Expand Up @@ -3,7 +3,7 @@ import Promise from 'bluebird';

const LOGGER = require('@calzoneman/jsli')('database/update');

const DB_VERSION = 11;
const DB_VERSION = 12;
var hasUpdates = [];

module.exports.checkVersion = function () {
Expand Down Expand Up @@ -51,6 +51,8 @@ function update(version, cb) {
addChannelLastLoadedColumn(cb);
} else if (version < 11) {
addChannelOwnerLastSeenColumn(cb);
} else if (version < 12) {
addUserInactiveColumn(cb);
}
}

Expand Down Expand Up @@ -128,3 +130,14 @@ function addChannelOwnerLastSeenColumn(cb) {
});
});
}

function addUserInactiveColumn(cb) {
db.query("ALTER TABLE users ADD COLUMN inactive BOOLEAN DEFAULT FALSE", error => {
if (error) {
LOGGER.error(`Failed to add inactive column: ${error}`);
cb(error);
} else {
cb();
}
});
}

0 comments on commit aa23486

Please sign in to comment.