问题
I have a method that I'd only like admins to be able to call, but I also want it to run in Meteor.onStartup(). How can I do this?
I've added "isAdmin": true to user documents that are admins and added an if statement to the beginning of methods that only admin should be able to call to check that this user is indeed an admin. This works great except that I want to call this method in onStartup too, but since there is no user when the onStartup code is run, the method can't be called. How can I get around this?
Thanks
回答1:
Refactor your shared code (that is run both in the method and in the startup function) into a separate function, and use it in both places:
var sharedFunction = function() {
// do something
};
Meteor.methods({
"foo": function() {
if (Meteor.user().isAdmin) {
sharedFunction();
}
}
}
Meteor.startup(sharedFunction);
回答2:
You can either refactor your common code into a function and call it from within your method within an if statement that checks for user or
you can use http://docs.meteor.com/#method_setUserId to temporarily set an admin user as logged in and then log out after your call completes.
For such purposes, you can create an account called system/maintenance etc.
来源:https://stackoverflow.com/questions/21763431/security-for-meteor-methods-while-allowing-server-to-run-code-too