meteor: impersonating a user
If you are lucky enough to have users, some of them will eventually want help. One of the easiest ways to understand and diagnose a problem, is to impersonate (log in as) the user who needs your assistance.
Although the docs don't say how to accomplish this, there is a simple and secure way to get it working with the existing meteor API. The goal is to convince the client and the server that you are a different user by calling setUserId
on both. This approach has been approved by a meteor core developer and we use it in production.
First we'll create a method called impersonate
, which calls setUserId
on the server if the caller is an admin.
Meteor.methods({
impersonate: function(userId) {
check(userId, String);
if (!Meteor.users.findOne(userId))
throw new Meteor.Error(404, 'User not found');
if (!Meteor.user().isAdmin)
throw new Meteor.Error(403, 'Permission denied');
this.setUserId(userId);
}
});
Next we'll write some template code that calls the method from the client. In this example, this.id
is the id of the user we wish to impersonate.
Template.impersonate.events({
'click .impersonate': function() {
var userId = this.id;
Meteor.call('impersonate', userId, function(err) {
if (!err) {
Meteor.connection.setUserId(userId);
Router.go('home');
}
});
}
});
In order to get your subscriptions to reset after swapping users, I'd recommend placing them inside of an autorun
.
Tracker.autorun(function() {
if (Meteor.userId()) {
Meteor.subscribe('rooms');
}
});
And that's it! Simply hit refresh or manually change the URL to stop impersonating.