Last active
July 6, 2018 17:08
-
-
Save danielpowell4/15472c309d68fbc4949969b3c85f92cf to your computer and use it in GitHub Desktop.
react-router and several other demos offer up a "fakeAuth". This is a starterAuth that sends an email and password to an external API and then stores the returned auth_token JWT in localStorage. Main benefit of doing so is to persist login between page refreshes.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import fetch from "cross-fetch"; | |
const apiUrl = "//localhost:5000"; // or where ever your api lives! | |
const checkStatus = response => { | |
if (response.status >= 200 && response.status < 300) { | |
return response; | |
} | |
const error = new Error(`${response.statusText}`); | |
error.status = response.statusText; | |
error.response = response; | |
throw error; | |
}; | |
const parseJSON = payload => { | |
if (typeof payload === "string") { | |
return JSON.parse(payload); | |
} | |
return payload.json(); | |
}; | |
export const starterAuth = { | |
auth_token: localStorage.getItem("auth_token"), | |
isAuthenticated() { | |
return !!this.auth_token; | |
}, | |
authenticate(email, password) { | |
return fetch(`${apiUrl}/auth/login`, { | |
method: "POST", | |
headers: { "Content-Type": "application/x-www-form-urlencoded" }, | |
body: `email=${email}&password=${password}` | |
}) | |
.then(checkStatus) | |
.then(parseJSON) | |
.then(({ auth_token }) => { | |
localStorage.setItem("auth_token", auth_token); | |
this.auth_token = auth_token; | |
return Promise.resolve(); | |
}); | |
}, | |
signout(cb) { | |
localStorage.removeItem("auth_token"); | |
this.auth_token = null; | |
return cb(); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment