Skip to content

Commit

Permalink
login screen
Browse files Browse the repository at this point in the history
  • Loading branch information
carolynzhuang committed Nov 14, 2024
1 parent 37c71bc commit 6e20f51
Showing 1 changed file with 70 additions and 0 deletions.
70 changes: 70 additions & 0 deletions src/screens/login/GoogleSignIn.tsx
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>
);
}

0 comments on commit 6e20f51

Please sign in to comment.