Allow user to delete their own account

I thought this would have been a common question but I am not finding anything to accomplish this task. I am trying to allow users to delete their own account but currently I am getting 403 errors “Access denied. No allow validators”. Is there something I am missing since the user is currently logged in - should I log them out first and then somehow trigger the deletion?

The code I am using is:

if (Meteor.isServer) {
    Meteor.users.allow({
        remove: function() {
            return true;
    });
}

Meteor.users.remove({ _id: this._id }, function(error, result) {
    if (error) {
        console.log("Error removing user: ", error);
    } else {
        console.log("Number of users removed: " + result);
    }
});

Have you tried putting the delete code in a Method?

Definitely make it a method, never allow users to delete anything directly from the client, especially such important data as user account.

Allow and deny should be placed in common code so the client sees it as well. I think the issue is that the client thinks it’s not allowed to remove users, even though by the rules on the server it could.

Deleting users who are still logged in shouldn’t be a problem.

I believe using this rule should be just as safe as using a method:

Meteor.users.allow({
    remove: function(userId,doc){
        return userId && userId === doc._id;
    }
});

Why not just make a Meteor method, and then not worry about Meteor’s allow/remove permissions (which are recommended against, anyway).

Meteor.methods({
  selfDelete() {
    if (!Meteor.isServer) return;

    try {
      Meteor.users.remove(this.userId);
    } catch (e) {
      // handle this however you want
      throw new Meteor.Error('self-delete', 'Failed to remove yourself');
    }
  },
});
2 Likes

Thanks everyone - I had tried the method route before but I was unsuccesful, I can’t remember what I was using but it wasn’t working. @ffxsam - your method works great, thank you. I plan on moving the users collection and method into an Astronomy ORM model in the future like I have with my other collections but I had several issues while trying to get that going that I tabled it for a later date.

3 Likes

Glad it helped!

I don’t know if merging the Meteor users collection into an ORM would be wise. It could possibly throw off some of the Meteor accounts-base internal processes.

1 Like

Thanks for the heads up. I was puzzled as to why it was giving me such a hard time because all of my other collections work great with Astronomy and ViewModel but now I know why.