Skip to content

Commit

Permalink
Persistent auth State with localStorage && Fixing Routing Errors …
Browse files Browse the repository at this point in the history
…using `withRouter()` from `react-router`
  • Loading branch information
Ch-sriram committed Sep 10, 2020
1 parent b12de68 commit c80a5e7
Show file tree
Hide file tree
Showing 4 changed files with 54 additions and 6 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -147,3 +147,4 @@ Dependency Installation: **`npm i --save redux-thunk`**
10. Adding a Logout Link: [Commit Details](https://github.com/Ch-sriram/burger-builder/commit/0a912cd59813270b92fb5a9bd6b89f5a71e16d19)
11. Forwarding Unauthenticated Users: [Commit Details](https://github.com/Ch-sriram/burger-builder/commit/9c7f59c8d90bb35c903253fd537cc92767fdc8d7)
12. Redirecting the User to the Checkout Page (In case the User is New and has Built a Burger w/o Login/Signup): [Commit Details](https://github.com/Ch-sriram/burger-builder/commit/35c2a66977084175b1c9bd14b42f5158c56ee736)
13. Persistent `auth` State with `localStorage` && Fixing Routing Errors using `withRouter()` from `react-router`: [Commit Details]()
14 changes: 12 additions & 2 deletions src/App.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// LIBRARY IMPORTS
import React, { Component } from 'react';
import { Route, Switch } from 'react-router-dom';
import { Route, Switch, withRouter } from 'react-router-dom';
import { connect } from 'react-redux';

// CUSTOM COMPONENTS
import Layout from './components/Layout/Layout.component';
Expand All @@ -9,8 +10,13 @@ import Checkout from './containers/Checkout/Checkout.component';
import Orders from './containers/Orders/Orders.component';
import Auth from "./containers/Auth/Auth.component";
import Logout from "./containers/Auth/Logout/Logout.component";
import * as actions from "./store/actions/index";

class App extends Component {
componentDidMount() {
this.props.onTryAutoSignup();
}

render() {
return (
<div>
Expand All @@ -28,4 +34,8 @@ class App extends Component {
}
}

export default App;
const mapDispatchToProps = dispatch => ({
onTryAutoSignup: () => dispatch(actions.authCheckState()),
});

export default withRouter(connect(null, mapDispatchToProps)(App));
44 changes: 40 additions & 4 deletions src/store/actions/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,12 @@ import * as actionTypes from './actionTypes';
export const authStart = () => ({ type: actionTypes.AUTH_START, });
export const authFail = error => ({ type: actionTypes.AUTH_FAIL, error, });
export const authSuccess = (idToken, userId) => ({ type: actionTypes.AUTH_SUCCESS, idToken, userId, });
export const logout = () => ({ type: actionTypes.AUTH_LOGOUT, });

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

export const checkAuthTimeout = expirationTime => dispatch => {
setTimeout(() => {
Expand All @@ -17,6 +22,8 @@ export const checkAuthTimeout = expirationTime => dispatch => {

export const auth = (email, password, isSignup) => dispatch => {
dispatch(authStart());

// Expected REQUEST BODY format for Firebase: https://firebase.google.com/docs/reference/rest/auth#section-create-email-password
const authData = {
email,
password,
Expand All @@ -27,15 +34,27 @@ export const auth = (email, password, isSignup) => dispatch => {
const API_KEY = "AIzaSyBCsIqRpXyn4Y3eYRikUd9uhe71UOq-NMA";

// Sign-In Link: https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=[API_KEY]
const signIn = "signInWithPassword", signUp = "signUp";
let url = isSignup ? `https://identitytoolkit.googleapis.com/v1/accounts:${signUp}?key=${API_KEY}`
const signIn = "signInWithPassword",
signUp = "signUp";
let url = isSignup
? `https://identitytoolkit.googleapis.com/v1/accounts:${signUp}?key=${API_KEY}`
: `https://identitytoolkit.googleapis.com/v1/accounts:${signIn}?key=${API_KEY}`;

axios
.post(url, authData)
.then((res) => {
console.log(res);
const { idToken, localId, expiresIn } = res.data;
console.log(idToken, localId, expiresIn);
// whenever we refresh the webapp, the login information
// is lost, and so, we will store the token for 3600
// seconds, which is 60 minutes = 1 hour, in our local
// state persistently using the localStorage API.
localStorage.setItem("token", idToken);
const expirationDate = new Date(new Date().getTime() + expiresIn * 1000);
console.log(expirationDate);
localStorage.setItem("expirationDate", expirationDate);
localStorage.setItem("userId", localId);
dispatch(authSuccess(idToken, localId));
dispatch(checkAuthTimeout(expiresIn));
})
Expand All @@ -46,3 +65,20 @@ export const auth = (email, password, isSignup) => dispatch => {
};

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

export const authCheckState = () => dispatch => {
const token = localStorage.getItem("token");
if (!token) {
dispatch(logout());
} else {
const expirationDate = new Date(localStorage.getItem("expirationDate"));
console.log(expirationDate);
if (expirationDate > new Date()) {
const userId = localStorage.getItem("userId");
dispatch(authSuccess(token, userId));
dispatch(checkAuthTimeout((expirationDate.getTime() - new Date().getTime()) / 1000));
} else {
dispatch(logout());
}
}
}
1 change: 1 addition & 0 deletions src/store/actions/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,5 @@ export {
auth,
logout,
setAuthRedirectPath,
authCheckState,
} from "./auth";

0 comments on commit c80a5e7

Please sign in to comment.