Possible authentication enhancement?
Kyii opened this issue · 2 comments
hey MacKentoch,
first of all thanks for putting together this great starter. i learned a lot about HOC and other more advanced stuff form your repo.
I am trying to enhance authentication a bit and maybe you could give me a little hint how you would approach this.
-
I want to avoid that authenticated users can access certain routes like login. Instead they should be redirected to dashboard. But i can't access props from
AuthProvider
inRoot.js
. So i tried (inRoot.js
):
<Route exact path="/login" render={() => auth.isAuthenticated() ? ( <Redirect to="/dashboard" /> ) : ( <LoadableLogin /> ) } />
but this killed theRouterHistory
withinLogin.js
? -
Where would you introduce authorization - like differentiating routing between different user roles like user and admin - in this setup? I tried to do this also in
Root.js
but still i can't get access to the necessary userInfo there.
Am i missing something about how to access contextAPI props in Root.js
?
Thanks for your time!
Greetings Kyii
Hi @Kyii ,
Thank you. Glad it helps.
- Protecting routes is done as suggested on react-router documentation.
Id behind is to make your own component specialized in private or protected route.
- See an example of application for Protected page: Routes needed to be authenticated.
- Adapt your authentication logic / tests in PrivateRoute component itself: PrivateRoute Component source -adjust on your own needs -
- Root is not supposed to be more than declaration, jsx of bare bone component / routers.
As Context providers are declared in Root you won't be able to use context consumer if you are not in inside provider.
But handling authentication is easily done:
- worst factorized case: in any scene (taking value from context and display only authorized content)
- better case: use withMainLayout that is a way to factorize and don't repeat the same code and logic for all wrapped scene components
- otherwise another better case alternative: create a specific PrivateRoute component and apply your auth logic from there (connect it to auth context to be aware of auth).
You cannot access a context if you are not inside its provider. So as I use Root just to declare root components logic should be inside Root's children.
Consumer could be used in Root jsx by rendering a function (like that) but you will loose the ability to access context in lifecycle so I dislike this way to use contexts.
@MacKentoch
Hi, thank you so much for pointing me in the right direction. Your approach is working very well.