reactql / example-auth

User auth, session & JWT example for ReactQL
48 stars 17 forks source link

how to handle unauthorized users #2

Closed tsdexter closed 7 years ago

tsdexter commented 7 years ago

Hi Lee,

Was hoping to see your approach to handling/routing unauthorized users. For example:

Any plans to include any of this in the example?

leebenson commented 7 years ago

No plans at this stage. The purpose of this example was mostly to outline one possible approach to how the communication between React and server could work, rather than create a full-blown auth module. I'm trying to impart the concepts, rather than the implementation.

With that said, if you look at https://github.com/reactql/example-auth/blob/master/src/components/user.js#L19, you can see that tackling 'unauthorised' users is possible by feeding in the session GraphQL query to component, and then simply reading if props.data.session.user has data. If it doesn't, they're not logged in.

You could use that as a basis for an <Authorized> component that checks for a loaded user, and sends back a <Redirect> from React Router if they're not loaded, or the child elements if they are. That'd allow you to use it like:

<Authorized>
  <StuffToShowWhenLoggedIn />
</Authorized>

... and <Authorized> would act as a HOC for redirecting to the login page if not authenticated.

tsdexter commented 7 years ago

Thanks @leebenson thats pretty similar to what I've implemented in a <CanAccess/> HOC in an existing ReactQL app. Just wanted to get a pros perspective.

leebenson commented 7 years ago

No prob. Sounds like you're on the right track.