This repository has been archived by the owner on Dec 22, 2023. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
auth.ts
73 lines (62 loc) · 2.42 KB
/
auth.ts
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
import { FirebaseAuthTypes } from "@react-native-firebase/auth";
import { FirebaseFunctionsTypes } from "@react-native-firebase/functions";
import { AuthError, useAuthRequest, useAutoDiscovery } from "expo-auth-session";
import { createURL } from "expo-linking";
import { getRandomBytes } from "expo-random";
import { useRef, useState } from "react";
export const useLinkBlueLogin = (fbAuth: FirebaseAuthTypes.Module, fbFunctions: FirebaseFunctionsTypes.Module): [boolean, () => void, FirebaseAuthTypes.UserCredential | null, AuthError | Error | null] => {
const discovery = useAutoDiscovery("https://login.microsoftonline.com/2b30530b-69b6-4457-b818-481cb53d42ae/v2.0");
const nonce = useRef(getRandomBytes(10).join(""));
const [
,, promptAsync
] = useAuthRequest({
clientId: "71e79019-a381-4be1-8625-a1978edc8d04",
redirectUri: createURL("auth"),
scopes: [
"openid", "profile", "email", "offline_access", "User.read"
],
responseType: "token",
extraParams: { nonce: nonce.current }
}, discovery);
const [ loading, setLoading ] = useState(false);
const [ error, setError ] = useState<AuthError | Error | null>(null);
const [ userCredential, setUserCredential ] = useState<FirebaseAuthTypes.UserCredential | null>(null);
const trigger = () => {
setLoading(true);
promptAsync({}).then(async (result) => {
// Try {
switch (result.type) {
case "success":
if (result.authentication?.accessToken == null) {
setError(new Error("Authentication popup reported success but no returned authentication data"));
break;
} else {
const generateCustomToken = fbFunctions.httpsCallable("generateCustomToken");
const customToken = await generateCustomToken({
accessToken: result.authentication.accessToken,
// Nonce: nonce.current
}) as { data: string };
setUserCredential(await fbAuth.signInWithCustomToken(customToken.data));
}
break;
case "error":
setError(result.error ?? null);
break;
case "cancel":
case "locked":
break;
default:
setError(new Error(`Unexpected result type: ${result.type}`));
break;
}
// } catch (error) {
// SetError(error as Error);
// } finally {
setLoading(false);
// }
}).catch(console.error);
};
return [
loading, trigger, userCredential, error
];
};