-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
37c71bc
commit 6e20f51
Showing
1 changed file
with
70 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,70 @@ | ||
import { useEffect, useState } from 'react'; | ||
import { Text, TouchableOpacity } from 'react-native'; | ||
import { makeRedirectUri } from 'expo-auth-session'; | ||
import * as Google from 'expo-auth-session/providers/google'; | ||
import * as WebBrowser from 'expo-web-browser'; | ||
import AsyncStorage from '@react-native-async-storage/async-storage'; | ||
import { styles } from './styles'; | ||
|
||
WebBrowser.maybeCompleteAuthSession(); | ||
|
||
export default function GoogleSignInButton() { | ||
const [userInfo, setUserInfo] = useState(null); | ||
const [request, response, promptAsync] = Google.useAuthRequest({ | ||
webClientId: process.env.EXPO_PUBLIC_GOOGLE_WEB_CLIENT_ID, | ||
androidClientId: process.env.EXPO_PUBLIC_GOOGLE_ANDROID_CLIENT_ID, | ||
iosClientId: process.env.EXPO_PUBLIC_GOOGLE_IOS_CLIENT_ID, | ||
redirectUri: makeRedirectUri({ scheme: 'org.calblueprint.ourcityforest' }), | ||
}); | ||
|
||
console.log(request); | ||
console.log(userInfo); | ||
|
||
useEffect(() => { | ||
handleSignInWithGoogle(); | ||
}, [response]); | ||
|
||
async function handleSignInWithGoogle() { | ||
try { | ||
const userJSON = await AsyncStorage.getItem('@user'); | ||
if (userJSON) { | ||
setUserInfo(JSON.parse(userJSON)); | ||
} else if ( | ||
response?.type === 'success' && | ||
response.authentication?.accessToken | ||
) { | ||
getUserInfo(response.authentication.accessToken); | ||
} | ||
} catch (error) { | ||
console.error('Error retrieving user data from AsyncStorage:', error); | ||
} | ||
} | ||
|
||
const getUserInfo = async (token: string) => { | ||
if (!token) return; | ||
try { | ||
const userResponse = await fetch( | ||
'https://www.googleapis.com/userinfo/v2/me', | ||
{ | ||
headers: { Authorization: `Bearer ${token}` }, | ||
}, | ||
); | ||
const user = await userResponse.json(); | ||
await AsyncStorage.setItem('@user', JSON.stringify(user)); | ||
setUserInfo(user); | ||
} catch (error) { | ||
console.error('Failed to fetch user data:', error); | ||
} | ||
}; | ||
|
||
return ( | ||
<TouchableOpacity | ||
style={styles.button} | ||
onPress={() => { | ||
promptAsync(); | ||
}} | ||
> | ||
<Text style={styles.buttonText}>Sign in with Google</Text> | ||
</TouchableOpacity> | ||
); | ||
} |