-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathindex.tsx
351 lines (307 loc) · 9.71 KB
/
index.tsx
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
import React, {
useState,
useMemo,
useEffect,
createContext,
useContext,
useCallback,
// types
ReactNode,
} from 'react';
import GoTrue, {
User as GoTrueUser,
Settings as GoTrueSettings,
} from 'gotrue-js';
import { runRoutes } from './runRoutes';
import { TokenParam, defaultParam } from './token';
type authChangeParam = (user?: User) => string | void;
export type Settings = GoTrueSettings;
export type User = GoTrueUser;
type Provider = 'bitbucket' | 'github' | 'gitlab' | 'google';
const defaultSettings = {
autoconfirm: false,
disable_signup: false,
external: {
bitbucket: false,
email: true,
facebook: false,
github: false,
gitlab: false,
google: false,
},
};
const errors = {
noUserFound: 'No current user found - are you logged in?',
noUserTokenFound: 'no user token found',
tokenMissingOrInvalid: 'either no token found or invalid for this purpose',
};
type MaybeUserPromise = Promise<User | undefined>;
export type ReactNetlifyIdentityAPI = {
user: User | undefined;
/** not meant for normal use! you should mostly use one of the other exported methods to update the user instance */
setUser: (_user: GoTrueUser | undefined) => GoTrueUser | undefined;
isConfirmedUser: boolean;
isLoggedIn: boolean;
signupUser: (
email: string,
password: string,
data: Object
) => MaybeUserPromise;
loginUser: (
email: string,
password: string,
remember?: boolean
) => MaybeUserPromise;
logoutUser: () => MaybeUserPromise;
requestPasswordRecovery: (email: string) => Promise<void>;
recoverAccount: (remember?: boolean) => MaybeUserPromise;
updateUser: (fields: { data: object }) => MaybeUserPromise;
getFreshJWT: () => Promise<string>;
authedFetch: {
get: (endpoint: string, obj?: {}) => Promise<any>;
post: (endpoint: string, obj?: {}) => Promise<any>;
put: (endpoint: string, obj?: {}) => Promise<any>;
delete: (endpoint: string, obj?: {}) => Promise<any>;
};
_goTrueInstance: GoTrue;
_url: string;
loginProvider: (provider: Provider) => void;
acceptInviteExternalUrl: (provider: Provider) => string;
settings: Settings;
param: TokenParam;
};
const [_useIdentityContext, _IdentityCtxProvider] = createCtx<
ReactNetlifyIdentityAPI
>();
export const useIdentityContext = _useIdentityContext; // we dont want to expose _IdentityCtxProvider
/** most people should use this provider directly */
export function IdentityContextProvider({
url,
children,
onAuthChange = () => {},
}: {
url: string;
children: ReactNode;
onAuthChange?: authChangeParam;
}) {
/******** SETUP */
if (!url || !validateUrl(url)) {
// just a safety check in case a JS user tries to skip this
throw new Error(
'invalid netlify instance URL: ' +
url +
'. Please check the docs for proper usage or file an issue.'
);
}
const identity = useNetlifyIdentity(url, onAuthChange);
return (
<_IdentityCtxProvider value={identity}>{children}</_IdentityCtxProvider>
);
}
/** some people may want to use this as a hook and bring their own contexts */
export function useNetlifyIdentity(
url: string,
onAuthChange: authChangeParam = () => {},
enableRunRoutes: boolean = true
): ReactNetlifyIdentityAPI {
const goTrueInstance = useMemo(
() =>
new GoTrue({
APIUrl: `${url}/.netlify/identity`,
setCookie: true,
}),
[url]
);
/******* STATE and EFFECTS */
const [user, setUser] = useState<User | undefined>(
goTrueInstance.currentUser() || undefined
);
const _setUser = useCallback(
(_user: User | undefined) => {
setUser(_user);
onAuthChange(_user); // if someone's subscribed to auth changes, let 'em know
return _user; // so that we can continue chaining
},
[onAuthChange]
);
const [param, setParam] = useState<TokenParam>(defaultParam);
useEffect(() => {
if (enableRunRoutes) {
const param = runRoutes(goTrueInstance, _setUser);
if (param.token || param.error) {
setParam(param);
}
}
}, []);
const [settings, setSettings] = useState<Settings>(defaultSettings);
useEffect(() => {
goTrueInstance.settings
.bind(goTrueInstance)()
.then(x => setSettings(x));
}, []);
/******* OPERATIONS */
// make sure the Registration preferences under Identity settings in your Netlify dashboard are set to Open.
// https://react-netlify-identity.netlify.com/login#access_token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1NTY0ODY3MjEsInN1YiI6ImNiZjY5MTZlLTNlZGYtNGFkNS1iOTYzLTQ4ZTY2NDcyMDkxNyIsImVtYWlsIjoic2hhd250aGUxQGdtYWlsLmNvbSIsImFwcF9tZXRhZGF0YSI6eyJwcm92aWRlciI6ImdpdGh1YiJ9LCJ1c2VyX21ldGFkYXRhIjp7ImF2YXRhcl91cmwiOiJodHRwczovL2F2YXRhcnMxLmdpdGh1YnVzZXJjb250ZW50LmNvbS91LzY3NjQ5NTc_dj00IiwiZnVsbF9uYW1lIjoic3d5eCJ9fQ.E8RrnuCcqq-mLi1_Q5WHJ-9THIdQ3ha1mePBKGhudM0&expires_in=3600&refresh_token=OyA_EdRc7WOIVhY7RiRw5w&token_type=bearer
/******* external oauth */
const loginProvider = useCallback(
(provider: Provider) => {
const url = goTrueInstance.loginExternalUrl(provider);
window.location.href = url;
},
[goTrueInstance]
);
const acceptInviteExternalUrl = useCallback(
(provider: Provider) => {
if (!param.token || param.type !== 'invite') {
throw new Error(errors.tokenMissingOrInvalid);
}
const url = goTrueInstance.acceptInviteExternalUrl(provider, param.token);
// clean up consumed token
setParam(defaultParam);
return url;
},
[goTrueInstance, param]
);
/******* email auth */
const signupUser = useCallback(
(
email: string,
password: string,
data: Object,
directLogin: boolean = true
) =>
goTrueInstance.signup(email, password, data).then(user => {
if (directLogin) {
return _setUser(user);
}
return user;
}),
[goTrueInstance, _setUser]
);
const loginUser = useCallback(
(email: string, password: string, remember: boolean = true) =>
goTrueInstance.login(email, password, remember).then(_setUser),
[goTrueInstance, _setUser]
);
const requestPasswordRecovery = useCallback(
(email: string) => goTrueInstance.requestPasswordRecovery(email),
[goTrueInstance]
);
const recoverAccount = useCallback(
(remember?: boolean) => {
if (!param.token || param.type !== 'recovery') {
throw new Error(errors.tokenMissingOrInvalid);
}
return goTrueInstance
.recover(param.token, remember)
.then(user => {
return _setUser(user);
})
.finally(() => {
// clean up consumed token
setParam(defaultParam);
});
},
[goTrueInstance, _setUser, param]
);
const updateUser = useCallback(
(fields: { data: object }) => {
if (!user) {
throw new Error(errors.noUserFound);
}
return user!
.update(fields) // e.g. { data: { email: "[email protected]", password: "password" } }
.then(_setUser);
},
[user]
);
const getFreshJWT = useCallback(() => {
if (!user) {
throw new Error(errors.noUserFound);
}
return user.jwt();
}, [user]);
const logoutUser = useCallback(() => {
if (!user) {
throw new Error(errors.noUserFound);
}
return user.logout().then(() => _setUser(undefined));
}, [user]);
const genericAuthedFetch = (method: string) => (
endpoint: string,
options: RequestInit = {}
) => {
if (!user?.token?.access_token) {
throw new Error(errors.noUserTokenFound);
}
const defaultObj = {
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
Authorization: 'Bearer ' + user.token.access_token,
},
};
const finalObj = Object.assign(defaultObj, { method }, options);
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'),
};
/******* hook API */
return {
user,
/** not meant for normal use! you should mostly use one of the other exported methods to update the user instance */
setUser: _setUser,
isConfirmedUser: !!(user && user.confirmed_at),
isLoggedIn: !!user,
signupUser,
loginUser,
logoutUser,
requestPasswordRecovery,
recoverAccount,
updateUser,
getFreshJWT,
authedFetch,
_goTrueInstance: goTrueInstance,
_url: url,
loginProvider,
acceptInviteExternalUrl,
settings,
param,
};
}
/**
*
*
* Utils
*
*/
function validateUrl(value: string) {
return /^(?:(?:(?:https?|ftp):)?\/\/)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))(?::\d{2,5})?(?:[/?#]\S*)?$/i.test(
value
);
}
// lazy initialize contexts without providing a Nullable type upfront
function createCtx<A>() {
const ctx = createContext<A | undefined>(undefined);
function useCtx() {
const c = useContext(ctx);
if (!c) throw new Error('useCtx must be inside a Provider with a value');
return c;
}
return [useCtx, ctx.Provider] as const;
}
// // Deprecated for now
// interface NIProps {
// children: any
// url: string
// onAuthChange?: authChangeParam
// }
// export default function NetlifyIdentity({ children, url, onAuthChange }: NIProps) {
// return children(useNetlifyIdentity(url, onAuthChange))
// }