Iron.Router: path matching for onBeforeAction


#1

I just starter teaching myself how to use Meteor and Iron.Router, and I’ve run into what must be a pretty common problem: I want to redirect users to a login page if they try to access a protected part of the site (in my case, that’s anything under the /app/ path. The Iron.Router docs mentioned in passing catchall routes; the example given was /(.*). This looked to me like it would match any route that matched the given regex. So, I tried the following:

loginRedirect = function() {
	if (!Meteor.userId()) {
		this.redirect('/login');
	} else {
		this.next();
	}
};

Router.onBeforeAction(loginRedirect, {
	only: ['/app/(.*)']
});

Predictably, however, this did absolutely nothing. Is there any easy way to have onBeforeAction trigger for some sort of regex path? I could add the login check to every single route, but that would be a lot of redundant code and would defeat the entire purpose of onBeforeAction.

Thanks in advance for any help!


#2

How if you inherit your protected routes from base controller.

Here is my sample code :

//Base controller.
BackController = RouteController.extend({  
    onBeforeAction: function () {            
        //Authenticate the user.
        if (!Roles.userIsInRole(Meteor.user(), ['admin'])) {
            this.redirect('auth');
        } else {
            this.layout('Back.layout');
            this.next();
        }
    }
});    

//Protected route.
Router.route('/admin/orders/q', {
    name: 'Back.orders',        
    //Inherited from base controller,
    controller: BackController.extend({
        template: 'Back.orders',
    })
});