Created
March 12, 2015 21:57
-
-
Save jperl/408119f2fbd190eabb7f to your computer and use it in GitHub Desktop.
Impersonate meteor user for development
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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