Jamgreen
Jamgreen

Reputation: 11039

Check if user exists in every route with Flow Router

I have a user profile in Meteor.

I am using Flow Router.

I want to check if the user exists on every route.

I have tried

const userRedirect = ( context, redirect, stop ) => {
  let userId = FlowRouter.getParam( 'userId' );

  if ( Meteor.users.find( { _id: userId } ).count() === 0 ) {
   FlowRouter.go( 'userList' );
  }
};

const projectRoutes = FlowRouter.group( {
  name: 'user',
  triggersEnter: [ userRedirect ]
} );

userRoutes.route( '/users/:userId', {
  name: 'userDetail',
  action: function ( params, queryParams ) {
    BlazeLayout.render( 'default', { yield: 'userDetail' } );
  },
} );

but it doesn't work.

I guess it's because I haven't subscribed to the user collection.

How can I do this in the route? Should I use

const userRedirect = ( context, redirect, stop ) => {
  let userId = FlowRouter.getParam( 'userId' );

  // subscribe to user
  Template.instance().subscribe( 'singleUser', userId );

  // check if found
  if ( Meteor.users.find( { _id: userId } ).count() === 0 ) {
   FlowRouter.go( 'userList' );
  }
};

Edit

I have tried checking in the template instead with

Template.userDetail.onCreated( () => {
  var userId = FlowRouter.getParam( 'userId' );
  Template.instance().subscribe( 'singleUser', userId );
});

Template.userDetail.helpers( {
  user: function () {
    var userId = FlowRouter.getParam( 'userId' );
    var user = userId ? Meteor.users.findOne( userId ) : null;
    return user;
  },
} );

but it will just populate the template with a variable user which is either the user object or null.

I want to use the notFound configuration offered by Flow Router for non-existing routes. I guess this can also be applied to 'non-existing data'.

So if a route path is /users/:userId and the user with the specific userId doesn't exists, the router should interpret the route as an invalid path.

Upvotes: 0

Views: 939

Answers (1)

Michel Floyd
Michel Floyd

Reputation: 20227

The FlowRouter documentation on auth logic and permissions recommends controlling what content is displayed to not logged-in vs. logged-in users in your templates rather than the router itself. iron-router patterns commonly do auth in the router.

For your specific question in your most recent question:

html:

{{#if currentUser}}
  {{> yield}}
{{else}}
  {{> notFoundTemplate}}
{{/if}}

To redirect using a trigger, try something along the lines of:

FlowRouter.route('/profile', {
  triggersEnter: [function(context, redirect) {
    if ( !Meteor.userId() ) redirect('/some-other-path');
  }]
});

Note that Meteor.userId() exists even when Meteor.user() hasn't been loaded yet.

docs

Upvotes: 1

Related Questions