0
votes

I have a component that the application goes through every time I change the screen. In this component I save isLogged: true in the state, a variable that tells me if I have logged in. When isLogged === true, I redirected to the home screen, when isLogged === false, I redirected to the signIn. If I log in, I enter my application and refresh the page (f5 or ctrl+r), lose the isLogged state and redirect me to signIn, because isLogged isn't true now. I wanted to know if there is any way to save the isLogged variable, so that refreshing the page (being logged in) does not redirect me back to signIn. I have tried to save the state in local storage, but I see it unsafe. This is my code:

export class Layout extends Component {

    constructor(props) {
        super(props);

        //definimos las variables necesarias
        this.state = { isLogged: false, usuarioLogado: any };

        //realizamos el bind de las funciones
        this.DoLogin = this.DoLogin.bind(this);
    }

    //funcion donde establecemos los valores de las variables
    DoLogin = (logged, usuario) =>
        this.setState({
            isLogged: logged,
            usuarioLogado: usuario
        });

    render() {
        if (this.state.isLogged) {
            return <div>
                <NavMenu headerTitle={this.props.headerTitle} textos={this.props.textos} valor={this.props.valor} changeLanguage={this.props.changeLanguage} usuario={this.state.usuarioLogado} labelData={this.props.labelData}/>
                {this.props.children}
            </div>
        }
        else return <SignIn callbackFromParent={this.DoLogin} labelData={this.props.labelData}/>;
    }
}
4
What kind of authentication are you using?zhuber
I use basic auth, log in with user and pass. @zhuberRichardSC
Best to save it in a cookie - npmjs.com/package/react-cookieHarmenx
Set to localStorage or sessionStorageDominic

4 Answers

1
votes

For this kind of cases in which you need a state to last far from a refresh, I'll recommend using LocalStorage because it could last in the browser with no problem, here's how you can use it:

export class Layout extends Component {
  //definimos las variables necesarias
  state = { isLogged: false, usuarioLogado: any };

  //funcion donde establecemos los valores de las variables
  DoLogin = (logged, usuario) => {
    localStorage.setItem('isLogged', true);
    this.setState({ isLogged: localStorage.getItem('isLogged'), usuarioLogado: usuario});
  };

   render() {
   const { changeLanguage, children, headerTitle, labelData, textos, valor } = this.props;
   const { isLogged, usuarioLogado } = tihs.state;

     if (isLogged) {
       return <div>
         <NavMenu headerTitle={headerTitle} textos={textos} valor={valor} changeLanguage={changeLanguage} usuario={usuarioLogado} labelData={labelData} />
                {children}
            </div>
        }
        else return <SignIn callbackFromParent={this.DoLogin} labelData={labelData}/>;
    }
}

Also, if you want to, you could check your LocalStorage collection in DevTools, in the Application tab, under LocalStorage (Chrome). This variable would be available for all your files, using the same calls as before.

0
votes

You could store it in cookie and read from cookie and set the value on init

OR you could store it in localStorage and read from it

OR You could also store it in indexedDB and read from it.

localStorage may be the easiest

https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/cookies https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API

The actual implementation would be in SignIn component, which checks and sets the value.

0
votes

You can save it in local storage. Basically this would be the flow

Once user initially enters your site (this includes refresh) check for local storage specified item (e.g. token):

  • if it exists set your state to isLoggedIn = true

  • if it doesn't exist set state to isLoggedIn = false and navigate to login

In case of login you'd be saving that token in your local storage after successful login and set isLoggedIn = true, but you'll also need to remove that item from local storage and set isLoggedIn = false when user logs out or any server call returns 401 (this slightly depends on your backend implementation).

0
votes

You have to store authentication data in browser storage or cookies.

If you receive some kind of token (in case of JWT) after user authentication, you can store it in browser localStorage (persisted between tabs) or sessionStorage (persisted inside current tab). If you want to increase security, you should invalidate or delete sensible information after some time of inactivity. The good practice is the invalidation of token after short time (the web service sends you new token before the current one gets expired, but after it gets expired, user hav to sign in again). This way prevents stealing the token for example, when user forgot to logout and moved away and left the browser opened.