[SOLVED] Iron Router: Trouble with redirecting user to login page if not logged in

Hi everyone, I’m trying to redirect users to a login template if they try to access other pages without being logged in. I found another forum topic on this (https://forums.meteor.com/t/has-anyone-implemented-the-redirect-to-login-then-redirect-to-requested-url-pattern-with-iron-router/2912/3) but now my separate user registration page (different template from login template) can never be reached by users who are logged out, which is the only time it would need to be accessed. So basically, I need a way to allow users to access the registration page even when logged out.

Here’s my router code:

//router config
Router.configure({
	layoutTemplate: 'main'
});

//routes
//redirects user to login page if not logged in
if(Meteor.isClient){
	var requireLogin = function(){
		if(!Meteor.user()){
			if(Meteor.loggingIn()){
				Router.go('home');
				this.next();
			}else{
				Router.go('login');
				this.next();
			}
		}else{
			this.next();
		}
	}

Router.onBeforeAction(requireLogin);

Router.route('/', {name: 'home'});
Router.route('/register');
Router.route('/login');
Router.route('/addbuilding');
Router.route('/buildings/:_id/edit', {
	name: 'edit_building',
	data: function() { return Buildings.findOne(this.params._id); }
});
Router.route('/submit', {name: 'buildingSubmit'});
}

I don’t think I need to show you my html for the login or registration pages, but basically there is a link to the registration page on the login page, and vice versa. Like I said, clicking the link on the login page to go to the registration page doesn’t do anything since the user isn’t logged in. Does anyone have any suggestions?

I figured it out. From reading the Iron Router documentation (http://iron-meteor.github.io/iron-router/#hooks under the subsection “Applying Hooks to Specific Routes”), I found out that you can just use ‘except’ to exclude the registration page from the other routing rules. Here’s my final code:

//router config
Router.configure({
	layoutTemplate: 'main'
});

//routes
if(Meteor.isClient){

	//redirects user to login page if not logged in
	var requireLogin = function(){
		if(!Meteor.user()){
			if(Meteor.loggingIn()){
				Router.go('home');
				this.next();
			} else{
				Router.go('login');
				this.next();
			}
		}else{
			this.next();
		}
	}

Router.onBeforeAction(requireLogin, {
	except: ['register']
});

Router.route('/', {name: 'home'});
Router.route('/register');
Router.route('/login');
Router.route('/addbuilding');
Router.route('/buildings/:_id/edit', {
	name: 'edit_building',
	data: function() { return Buildings.findOne(this.params._id); }
});
Router.route('/submit', {name: 'buildingSubmit'});
}

I hope this helps anyone who runs into a similar problem.

1 Like

Thanks for sharing this. It helped me