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


#1

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.


#2

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


#3

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?


#4

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'});
    }
});

#5

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.


#6

I wrote a guide here: