Created
July 8, 2019 23:59
-
-
Save camwhite/0738a66b61088d71e7a919adf881ae96 to your computer and use it in GitHub Desktop.
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
export const setSessionIdToken = (token) => | |
sessionStorage.setItem('id_token', token) | |
export const setLocalIdToken = (token) => | |
localStorage.setItem('id_token', token) | |
export const getIdToken = () => | |
sessionStorage.getItem('id_token') || localStorage.getItem('id_token') | |
export const requireAuth = (nextState, replaceState) => { | |
if (!getIdToken()) { | |
replaceState({ nextPathname: nextState.location.pathname }, '/') | |
} | |
} | |
const checkStatus = (response) => { | |
const { ok, statusText } = response | |
if (!ok) { | |
throw new Error(statusText) | |
} | |
return response | |
} | |
export const authenticate = (route, credentials) => { | |
return fetch(`/auth/${route}`, { | |
method: 'post', | |
headers: { | |
'Accept': 'application/json', | |
'Content-Type': 'application/json' | |
}, | |
body: JSON.stringify(credentials) | |
}) | |
.then(checkStatus) | |
.then(response => response.json()) | |
} | |
export const fetchCurrentUser = () => { | |
const jwt = getIdToken() | |
const headers = { 'Authorization': `Bearer ${jwt}` } | |
return fetch('/api/users/me', { headers: headers }) | |
.then(checkStatus) | |
.then(response => response.json()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment