Search code examples
javascriptauthenticationmeteorreactjsflow-router

Authentication in main component in react js


I am want to create a user based application by using meteor (v1.3). Hence the authentication and authorization is the core for the app. I came across this excellent example that wrote by flow router author which explains how to do the authentication and authorization with flow router.

https://github.com/alanning/meteor-roles/tree/master/examples/flow-router-advanced However this example is using Blaze for demonstration. I would like to know is it possible do the same thing with react.

The hardest part for me in order to convert it to react is that, it uses template level to do site-wide authentication. At this point I don't know how can it done in react.

Let say I have a Main layout component:

export const MainLayout = ({content}) => (

    <div className="container">

                {content}

    </div>
);

How can I do the authentication in this layout? Although, I know I can do it in the router , but the whole point of flow router is being non-reactive and predictable. The Flow router author also recommended to do it on the template layer, just as he did in the example above.

React is the new thing for me, I might be misunderstood the concept of react. Thus if you guys think this is not the ideal way to do so, please guide me to the correct path.


Solution

  • To bind Meteor's reactive variables to React components in Meteor 1.3+, use the createContainer function:

    export const MainLayout = createContainer(() => {
      return {
        isAdmin: Roles.userIsInRole(Meteor.userId(), ['admin']),
        userName: Meteor.user() ? Meteor.user().username : null
      }
    }, (props) => {
      if (!props.isAdmin) {
        return <p>No cake for you.</p>
      }
      return <div className="container">
        <p>Hello {props.userName}</p>
        {props.content}
      </div>;
    });
    

    createContainer extends the props object with the return value of the callback function you provide. If you access a reactive value in that function (like Meteor.user() above), it will be re-evaluated whenever that value changes. Type Meteor.logout() in the browser console, and watch the component react instantly.

    For a fully fledged tutorial, check out https://www.meteor.com/tutorials/react/collections.