Meteor Guide & Authenticated Routes?

I think it would be hugely beneficial to add a small section to the guide that gives a simple example of how “best” to structure the router for authenticating routes, when discussing both React Router and Flow Router.

Perhaps with both a simple “is logged in” example and a “user has role X” example?

As I am currently trying to figure out how best to integrate https://github.com/alanning/meteor-roles with React Router to limit access to certain routes, there seems to be a variety of different ways:

Using onEnter: https://github.com/reactjs/react-router/blob/master/examples/auth-flow/app.js (but this won’t be reactive!)
Using components: https://alexgaribay.com/2015/10/13/authenticated-routes-with-meteor-and-react-router/
etc.

Also, I know that the Roles need to be published to the client in order for the Roles.userIsInRole to return a valid value, so I auto-publish them currently:

// Publish client roles to all clients,
// without needing a subscription
Meteor.publish(null, function () {
  this.unblock();
  return Meteor.roles.find({});
});

But in the authentication I guess I still need to wait for the publication to be ready before redirecting, as they may have the correct role and it’s just not yet available?

EDIT: Perhaps I’m wrong about publishing the Roles collection: https://github.com/alanning/meteor-roles#changes-to-default-meteor-behavior

Wouldn’t this belong in the routing article?

@sashko yes, sorry… I don’t really mind where the information is, just that it would be useful to have it there!

I’ve tried using React Router and I’m coming across the following problems when using a simple onEnter function to check authentication:

  • If you are on an authenticated route and you force refresh, initially Meteor.user() is undefined, but Meteor.loggingIn() is true. But the onEnter method only runs the once (as it’s not reactive), so it can either redirect to the login page (wrongly) or let them into the route before they are effectively logged in (also wrong).
  • If a logout is forced from the server side, the user won’t be presented with the login page until they attempt to change routes, as the routing isn’t reactive.

So I’m sure that using onEnter callbacks isn’t the “recommended” way with Meteor as it should be able to be done much more reactively, but there doesn’t seem to be a best-practice.

The recommendation, which is admittedly very hard to find, is to do it in your template/component:

So in React, you would have something in your createContainer or getMeteorData that waits for the user data to load, then traverses to the correct route. There’s an issue open to make this easier to find:

Yeah, I guess the idea of having (in React) a wrapping component that handles all the authentication logic makes sense, but I was hoping for something a little more React Router specific, as it seems that is what the example TODO app is being built with (the React version at least!).