Skip to main content

18.16 Persistent Auth State with localStorage

auth.js

src\store\actions\auth.js
import axios from "axios";
import * as actionTypes from "./actionTypes";

export const authStart = () => {
return {
type: actionTypes.AUTH_START,
};
};

export const authSuccess = (token, userId) => {
return {
type: actionTypes.AUTH_SUCCESS,
idToken: token,
userId: userId,
};
};

export const authFail = (error) => {
return {
type: actionTypes.AUTH_FAIL,
error: error,
};
};

export const logout = () => {
localStorage.removeItem("token");
localStorage.removeItem("expirationDate");
localStorage.removeItem("userId");
return {
type: actionTypes.AUTH_LOGOUT,
};
};

export const checkAuthTimeout = (expirationTime) => {
return (dispatch) => {
setTimeout(() => {
dispatch(logout());
}, expirationTime * 1000);
};
};

export const auth = (email, password, isSignup) => {
return (dispatch) => {
dispatch(authStart());
const authData = {
email: email,
password: password,
returnSecureToken: true,
};
let url =
"https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=AIzaSyDsmwPeH2yE7yqvoeYolCLgB9ju50rYivo";
if (!isSignup) {
url =
"https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=AIzaSyDsmwPeH2yE7yqvoeYolCLgB9ju50rYivo";
}
axios
.post(url, authData)
.then((response) => {
console.log(response);
const expirationDate = new Date(
new Date().getTime() + response.data.expiresIn * 1000
);
localStorage.setItem("token", response.data.idToken);
localStorage.setItem("expirationDate", expirationDate);
localStorage.setItem("userId", response.data.localId);
dispatch(authSuccess(response.data.idToken, response.data.localId));
dispatch(checkAuthTimeout(response.data.expiresIn));
})
.catch((err) => {
dispatch(authFail(err.response.data.error));
});
};
};

export const setAuthRedirectPath = (path) => {
return {
type: actionTypes.SET_AUTH_REDIRECT_PATH,
path: path,
};
};

export const authCheckState = () => {
return (dispatch) => {
const token = localStorage.getItem("token");
if (!token) {
dispatch(logout());
} else {
const expirationDate = new Date(localStorage.getItem("expirationDate"));
if (expirationDate > new Date()) {
dispatch(logout());
} else {
const userId = localStorage.getItem("userId");
dispatch(authSuccess(token, userId));
dispatch(
checkAuthTimeout(
expirationDate.getsSeconds() - new Date().getSeconds()
)
);
}
}
};
};

index.js

src\store\actions\index.js
export { auth, authCheckState, logout, setAuthRedirectPath } from "./auth";
export {
addIngredient,
initIngredients,
removeIngredient,
} from "./burgerBuilder";
export { fetchOrders, purchaseBurger, purchaseInit } from "./order";

App.js

src\App.js
import React, { Component } from "react";
import { connect } from "react-redux";
import { Route, Switch } from "react-router-dom";
import Layout from "./components/Layout/Layout";
import Auth from "./containers/Auth/Auth";
import Logout from "./containers/Auth/Logout/Logout";
import BurgerBuilder from "./containers/BurgerBuilder/BurgerBuilder";
import Checkout from "./containers/Checkout/Checkout";
import Orders from "./containers/Orders/Orders";
import * as actions from "./store/actions/index";

class App extends Component {
componentDidMount() {
this.props.onTryAutoSignup();
}
render() {
return (
<div>
<Layout>
<Switch>
<Route path="/checkout" component={Checkout} />
<Route path="/orders" component={Orders} />
<Route path="/auth" component={Auth} />
<Route path="/logout" component={Logout} />
<Route path="/" exact component={BurgerBuilder} />
</Switch>
</Layout>
</div>
);
}
}

const mapDispatchtoProps = (dispatch) => {
return {
onTryAutoSignup: () => dispatch(actions.authCheckState()),
};
};

export default connect(null, mapDispatchtoProps)(App);