Authentication for public pages
There is a problem with the way the <RequireAuth>
component works right now: the process of checking if the user is logged in and the process of redirecting non-logged in users to the login page are tied together.
Why is this a problem
We may need to read user data even on pages that do not require authentication to access, for example in a public page which has a navigation bar on top which changes if the user is logged in or not. With the current implementation, if we land on such a page directly (i.e. not by navigating from an authenticated page via CSR) or hit refresh on it, the page will not try to authenticate and there will be no information about the logged in user in the navigation bar, even if the user is logged in.
Desired behavior
We need a way to be able to perform authentication without redirecting non-authenticated users
Possible solutions
- I would suggest creating two different components for these tasks: one for authenticating and one for blocking non-authenticated users from viewing the page. The first component would wrap all the routes, so that the user query will always be fired, regardless if the current page requires a login or not. The second component will wrap only pages that are not available to non-logged in users, and will redirect to some other page (login) if the user is not logged in (like the current
<RequireAuth>
minus thecurrentUserQuery
) - Another solution would be to add a
allowNonAuthenticatedUsers
prop to<RequireAuth>
and use it in the redirect condition:
if (!allowNonAuthenticatedUsers && (!token || error)) {
/* redirect to login page */
}
This would be more verbose in usage, because it would require to wrap every page component with <RequireAuth>
and pass allowNonAuthenticatedUsers
to the public ones, but it would be backward compatible and would not break any other project that's currently using the wrapper like it is now.