UNPKG

2.16 kBJavaScriptView Raw
1// @flow
2
3import {
4 NativeModules,
5} from 'react-native';
6
7import * as Constants from './Constants';
8
9const Google = NativeModules.ExponentGoogle;
10
11type LogInConfig = {
12 androidClientId?: string,
13 androidStandaloneAppClientId?: string,
14 iosClientId?: string,
15 iosStandaloneAppClientId?: string,
16 behavior?: 'system' | 'web',
17 scopes?: Array<string>,
18};
19
20type LogInResult = {
21 type: 'cancel',
22} | {
23 type: 'success',
24 accessToken: string,
25 idToken: ?string,
26 refreshToken: ?string,
27 serverAuthCode: ?string,
28 user: {
29 id: string,
30 name: string,
31 givenName: string,
32 familyName: string,
33 photoUrl?: ?string,
34 email?: ?string,
35 },
36};
37
38export async function logInAsync(
39 config: LogInConfig
40): Promise<LogInResult> {
41 let behavior = config.behavior;
42 if (!behavior) {
43 behavior = 'system';
44 }
45
46 // Only standalone apps can use system login.
47 if (behavior === 'system' && Constants.appOwnership !== 'standalone') {
48 behavior = 'web';
49 }
50
51 let scopes = config.scopes;
52 if (!scopes) {
53 scopes = ['profile', 'email'];
54 }
55
56 const androidClientId = Constants.appOwnership === 'standalone' ?
57 config.androidStandaloneAppClientId :
58 config.androidClientId;
59 const iosClientId = Constants.appOwnership === 'standalone' ?
60 config.iosStandaloneAppClientId :
61 config.iosClientId;
62
63 const logInResult = await Google.logInAsync({
64 androidClientId,
65 iosClientId,
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
72 // as the native login 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}