diff --git a/api/accounts/remove.js b/api/accounts/remove.js index 946e5a1..5af4c54 100644 --- a/api/accounts/remove.js +++ b/api/accounts/remove.js @@ -2,10 +2,19 @@ module.exports = removeAccount var deleteAccount = require('../../utils/account/delete') -function removeAccount (state, username, options) { +function removeAccount (state, idOrObject, options) { + var id + var username + if (typeof idOrObject === 'string') { + id = idOrObject + } else { + id = idOrObject.id + username = idOrObject.username + } return new Promise(function (resolve, reject) { deleteAccount({ couchUrl: state.url, + id: id, username: username, bearerToken: options.bearerToken, includeProfile: options.include === 'account.profile' diff --git a/routes/account.js b/routes/account.js index 5e6cf64..11fbc41 100644 --- a/routes/account.js +++ b/routes/account.js @@ -101,7 +101,9 @@ function accountRoutes (server, options, next) { }) .then(function (session) { - return accounts.remove(session.account.username, { + return accounts.remove({ + username: session.account.username + }, { bearerToken: sessionId, include: request.query.include }) diff --git a/routes/accounts.js b/routes/accounts.js index 1711d5e..6d64110 100644 --- a/routes/accounts.js +++ b/routes/accounts.js @@ -160,11 +160,37 @@ function accountRoutes (server, options, next) { } } + var deleteAccountRoute = { + method: 'DELETE', + path: prefix + '/accounts/{id}', + config: { + auth: false, + validate: { + headers: validations.bearerTokenHeader, + failAction: joiFailAction + } + }, + handler: function (request, reply) { + var sessionId = toBearerToken(request) + + return accounts.remove(request.params.id, { + bearerToken: sessionId + }) + + .then(function (/* json */) { + reply().code(204) + }) + + .catch(reply) + } + } + server.route([ postAccountsRoute, getAccountsRoute, getAccountRoute, - patchAccountRoute + patchAccountRoute, + deleteAccountRoute ]) next() diff --git a/utils/account/delete.js b/utils/account/delete.js index 3f7930a..8ed7c72 100644 --- a/utils/account/delete.js +++ b/utils/account/delete.js @@ -9,6 +9,33 @@ function deleteAccount (options, callback) { timeout: 10000 // 10 seconds }) + if (!options.username) { + return request.get({ + url: '/_users/_design/byId/_view/byId?key=' + options.id, + headers: { + cookie: 'AuthSession=' + options.bearerToken + } + }, function (error, response, body) { + if (error) { + return callback(Boom.wrap(error)) + } + + if (response.statusCode >= 400) { + return callback(Boom.create(response.statusCode, body.reason)) + } + + if (body.rows.length === 0) { + return callback(Boom.notFound()) + } + options.username = body.rows[0].id.substr('org.couchdb.user:'.length) + return sendDeleteRequest(request, options, callback) + }) + } + + sendDeleteRequest(request, options, callback) +} + +function sendDeleteRequest (request, options, callback) { request.del({ url: '/_users/org.couchdb.user:' + encodeURIComponent(options.username), headers: {