I have a synchronized onBeforeAction method with meteor.js
Router.onBeforeAction(function() {
var self;
self = this;
authToken = Session.get('authToken');
if (!authToken) {
this.redirect('login');
this.next();
} else {
Meteor.call('validateAuthToken', authToken, function (error, result)) {
if (result) {
self.next();
} else {
self.redirect('login');
self.next();
}
}
}
});
I need to validate an authentication token stored in Session by invoking a server call. But this method always throws an exception when I am executing it. And I found out the reason is because the onBeforeAction call is terminated before the validateAuthToken call returns. And thus the self.next() won't take action. So I wonder what can I do to prevent the onBeforeAction call from stopping until the validateAuthToken returns the validated result and then proceed?
I've tried a different implementation by wait on a session variable, but it seems the ready state is never set to true
Router.onBeforeAction(function() {
var authToken;
authToken = Session.get('authToken');
if (!authToken) {
this.redirect('login');
this.next();
} else {
Meteor.call('validateAuthToken', authToken, function (error, result) {
if (!error) {
Session.set("tokenValidated", result);
}
});
this.wait(Meteor.subscribe('token', Session.get('tokenValidated')));
if (this.ready()) {
if (!Session.get("tokenValidated")) {
this.redirect('login');
this.next();
} else {
this.next();
}
}
}
});
EDIT : After working with this problem for a little bit I came up with a working example (without the infinite loop). You can use the following code:
Which is called from waitOn like so:
I wrote a blog post with a more in depth explanation, which you can find here:
http://www.curtismlarson.com/blog/2015/05/04/meteor-ironrouter-waitOn-server/
You can also use this code snippet from https://github.com/iron-meteor/iron-router/issues/426