MacKentoch / react-bootstrap-webpack-starter

ReactJS 16.11 + new React Context API +react Router 4 + webpack 4 + babel 7+ hot Reload + Bootstrap 4 + styled-components
114 stars 37 forks source link

Possible authentication enhancement? #9

Closed Kyii closed 5 years ago

Kyii commented 5 years ago

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.

  1. 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 in Root.js. So i tried (in Root.js):
    <Route exact path="/login" render={() => auth.isAuthenticated() ? ( <Redirect to="/dashboard" /> ) : ( <LoadableLogin /> ) } /> but this killed the RouterHistory withinLogin.js?

    1. 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

MacKentoch commented 5 years ago

Hi @Kyii ,

Thank you. Glad it helps.

  1. Protecting routes is done as suggested on react-router documentation. Id behind is to make your own component specialized in private or protected route.
  1. 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:

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.

Kyii commented 5 years ago

@MacKentoch Hi, thank you so much for pointing me in the right direction. Your approach is working very well.