Skip to content

Instantly share code, notes, and snippets.

@camwhite
Created July 8, 2019 23:59
Show Gist options
  • Save camwhite/0738a66b61088d71e7a919adf881ae96 to your computer and use it in GitHub Desktop.
Save camwhite/0738a66b61088d71e7a919adf881ae96 to your computer and use it in GitHub Desktop.
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