Skip to content

Instantly share code, notes, and snippets.

@jperl
Created March 12, 2015 21:57
Show Gist options
  • Save jperl/408119f2fbd190eabb7f to your computer and use it in GitHub Desktop.
Save jperl/408119f2fbd190eabb7f to your computer and use it in GitHub Desktop.
Impersonate meteor user for development
// Server
Meteor.methods({
/**
* Login as a userId. Must be an admin.
*/
impersonate: function (options) {
var self = this;
if (Settings.isProduction) {
var currentUser = Meteor.users.findOne(self.userId);
if (! currentUser || ! currentUser.admin) {
throw new Meteor.Error('You do not have permission to add companies.');
}
}
check(options, {
_id: Match.Optional(String),
alias: Match.Optional(String)
});
return Accounts._loginMethod(this, 'impersonate', arguments, 'impersonate', function () {
var user = Meteor.users.findOne(options);
if (! user) throw new Meteor.Error('User not found');
// Log the current user out.
currentUser && Accounts._setLoginToken(currentUser._id, self.connection, null);
return { userId: user._id };
});
}
});
// Client
var loginTokenKey = 'Meteor.loginToken',
loginTokenExpiresKey = 'Meteor.loginTokenExpires';
var impersonate = function (options, callback) {
Meteor.call('impersonate', options, function (error, result) {
if (error) {
callback && callback.apply(this, arguments);
return;
}
// this will update Meteor.user()
Accounts.connection.setUserId(result.userId);
// set the login token so fast-render will work
Meteor._localStorage.setItem(loginTokenKey, result.token);
Meteor._localStorage.setItem(loginTokenExpiresKey, result.tokenExpires);
callback && callback.apply(this, arguments);
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment