UNPKG

2.29 kBJavaScriptView Raw
1// @flow
2
3import { NativeModules } from 'react-native';
4
5import Constants from './Constants';
6
7const Google = NativeModules.ExponentGoogle;
8
9type LogInConfig = {
10 androidClientId?: string,
11 androidStandaloneAppClientId?: string,
12 iosClientId?: string,
13 iosStandaloneAppClientId?: string,
14 webClientId?: string,
15 behavior?: 'system' | 'web',
16 scopes?: Array<string>,
17};
18
19type LogInResult =
20 | {
21 type: 'cancel',
22 }
23 | {
24 type: 'success',
25 accessToken?: ?string,
26 idToken: ?string,
27 refreshToken: ?string,
28 serverAuthCode: ?string,
29 user: {
30 id: string,
31 name: string,
32 givenName: string,
33 familyName: string,
34 photoUrl?: ?string,
35 email?: ?string,
36 },
37 };
38
39export async function logInAsync(config: LogInConfig): Promise<LogInResult> {
40 let behavior = config.behavior;
41 if (!behavior) {
42 behavior = 'system';
43 }
44
45 // Only standalone apps can use system login.
46 if (behavior === 'system' && Constants.appOwnership !== 'standalone') {
47 behavior = 'web';
48 }
49
50 let scopes = config.scopes;
51 if (!scopes) {
52 scopes = ['profile', 'email'];
53 }
54
55 const androidClientId =
56 Constants.appOwnership === 'standalone'
57 ? config.androidStandaloneAppClientId
58 : config.androidClientId;
59 const iosClientId =
60 Constants.appOwnership === 'standalone' ? config.iosStandaloneAppClientId : config.iosClientId;
61
62 const logInResult = await Google.logInAsync({
63 androidClientId,
64 iosClientId,
65 webClientId: config.webClientId,
66 behavior,
67 scopes,
68 });
69
70 if (behavior === 'web') {
71 // Web login only returns an accessToken so use it to fetch the same info as the native login
72 // does.
73 let userInfoResponse = await fetch('https://www.googleapis.com/userinfo/v2/me', {
74 headers: { Authorization: `Bearer ${logInResult.accessToken}` },
75 });
76 userInfoResponse = await userInfoResponse.json();
77 return {
78 ...logInResult,
79 user: {
80 id: userInfoResponse.id,
81 name: userInfoResponse.name,
82 givenName: userInfoResponse.given_name,
83 familyName: userInfoResponse.family_name,
84 photoUrl: userInfoResponse.picture,
85 email: userInfoResponse.email,
86 },
87 };
88 } else {
89 return logInResult;
90 }
91}