forked from kentcdodds/bookshelf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth-provider.js
51 lines (41 loc) · 1.51 KB
/
auth-provider.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// pretend this is firebase, netlify, or auth0's code.
// you shouldn't have to implement something like this in your own app
const localStorageKey = '__auth_provider_token__'
async function getToken() {
// if we were a real auth provider, this is where we would make a request
// to retrieve the user's token. (It's a bit more complicated than that...
// but you're probably not an auth provider so you don't need to worry about it).
return window.localStorage.getItem(localStorageKey)
}
function handleUserResponse({user}) {
window.localStorage.setItem(localStorageKey, user.token)
return user
}
function login({username, password}) {
return client('login', {username, password}).then(handleUserResponse)
}
function register({username, password}) {
return client('register', {username, password}).then(handleUserResponse)
}
async function logout() {
window.localStorage.removeItem(localStorageKey)
}
// an auth provider wouldn't use your client, they'd have their own
// so that's why we're not just re-using the client
const authURL = process.env.REACT_APP_AUTH_URL
async function client(endpoint, data) {
const config = {
method: 'POST',
body: JSON.stringify(data),
headers: {'Content-Type': 'application/json'},
}
return window.fetch(`${authURL}/${endpoint}`, config).then(async response => {
const data = await response.json()
if (response.ok) {
return data
} else {
return Promise.reject(data)
}
})
}
export {getToken, login, register, logout, localStorageKey}