-
Notifications
You must be signed in to change notification settings - Fork 9
/
useNetlifyIdentity.js
61 lines (58 loc) · 1.88 KB
/
useNetlifyIdentity.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
52
53
54
55
56
57
58
59
60
61
import React from 'react';
// -------------- usage --------------
import netlifyIdentity from 'netlify-identity-widget';
import { useLocalStorage } from '@swyx/hooks';
netlifyIdentity.init();
export default function useNetlifyIdentity(onAuthChange) {
if (!onAuthChange) throw new Error('onAuthChange cannot be falsy');
const itemChangeCallback = _user => {
if (_user) {
const faunadb_token =
_user && _user.app_metadata && _user.app_metadata.faunadb_token;
if (faunadb_token) onAuthChange(faunadb_token);
else {
console.error(
'Expected _user to have a faunadb_token, check logs for the identity-signup.js function.'
);
}
} else {
onAuthChange(null);
}
};
const [item, setItem, removeItem] = useLocalStorage(
'faunaNetlifyUser',
itemChangeCallback
);
React.useEffect(() => {
netlifyIdentity.on('login', setItem);
netlifyIdentity.on('logout', removeItem);
}, []);
// definition - `item` comes from useNetlifyIdentity hook
const genericAuthedFetch = method => (endpoint, obj = {}) => {
if (!item || !item.token || !item.token.access_token)
throw new Error('no user token found');
const defaultObj = {
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
Authorization: 'Bearer ' + item.token.access_token
}
};
const finalObj = Object.assign(defaultObj, { method }, obj);
return fetch(endpoint, finalObj).then(res =>
finalObj.headers['Content-Type'] === 'application/json' ? res.json() : res
);
};
const authedFetch = {
get: genericAuthedFetch('GET'),
post: genericAuthedFetch('POST'),
put: genericAuthedFetch('PUT'),
delete: genericAuthedFetch('DELETE')
};
return {
user: item,
doLogout: () => netlifyIdentity.logout(),
doLogin: () => netlifyIdentity.open(),
authedFetch
};
}