Flow Router, redirect any route if user is not logged in?

My application requires a logged in user to use. Whenever someone navigates to my app, no matter how they enter the app, I want to render a login template if the user is not logged in.

I would assume what i could do, is in each of my routes, manually check in an if() statement if theres a logged in user, and if not manually redirect to the login template. Of course, this would just be me repeating code.

Is there a simpler way to prevent a user from using the app without being logged in with FlowRouter? Also using BlazeLayout currently, if that matters.

In your global template, call a global helper that checks login and redirects if user not logged in.

so just something like:

{{#if currentUser}}
    {{> content}}
{{else}}
    {{> login}}
{{/if}}

Is that’s all that would be needed? Are there any workarounds the user could do client side to get around that?

Use group and authenticate user using triggersEnter

const adminRoutes = FlowRouter.group({
    prefix: '/admin',
    triggersEnter: [
        (context, redirect) => {
            if (!Roles.userIsInRole(Meteor.userId(), 'admin')) {
                redirect('/admin/login');
            }
        }
    ]
});

adminRoutes.route('/', {
    action () {
        mount(Admin, {content: 'home'});
    }
});

adminRoutes.route('/profile', {
    action () {
        mount(Admin, {content: 'profile'});
    }
});
3 Likes

That’s all you need.
You don’t need to worry about client workarounds, as normally, you are not providing any useful data until they log in (so no security issue there). If they are really sneaky, they’ll override Meteor.userId() or other functions and get around your #if, but that would be totally useless (almost stateless), so don’t worry about it.

I wrote a guide here:

1 Like