Skip to content

Add Google Sign-In login screen #3

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ CodeBuilder Admin is a mobile application built with React Native and Expo. This

```env
GOOGLE_MAPS_API_KEY=your_google_maps_api_key
GOOGLE_WEB_CLIENT_ID=your_google_web_client_id
FIREBASE_API_KEY=your_firebase_api_key
FIREBASE_AUTH_DOMAIN=your_firebase_auth_domain
FIREBASE_PROJECT_ID=your_firebase_project_id
Expand Down
2 changes: 2 additions & 0 deletions app.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ module.exports = {
firebaseStorageBucket: process.env.FIREBASE_STORAGE_BUCKET,
firebaseMessagingSenderId: process.env.FIREBASE_MESSAGING_SENDER_ID,
firebaseAppId: process.env.FIREBASE_APP_ID,
googleWebClientId: process.env.GOOGLE_WEB_CLIENT_ID,
},
orientation: "portrait",
icon: "./assets/images/icon.png",
Expand Down Expand Up @@ -135,6 +136,7 @@ module.exports = {
],
"@react-native-firebase/app",
"@react-native-firebase/messaging",
"@react-native-google-signin/google-signin",
// Add the iOS sound plugin
[withIOSSounds],
[
Expand Down
16 changes: 13 additions & 3 deletions app/_layout.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useEffect, useState } from "react";
import { useEffect } from "react";
import { useNavigationContainerRef } from "@react-navigation/native";
import { useReactNavigationDevTools } from "@dev-plugins/react-navigation";
import { SplashScreen } from "expo-router";
Expand All @@ -18,6 +18,7 @@ import "react-native-reanimated";
import { useColorScheme } from "@/hooks/useColorScheme";
import { registerBackgroundFetch } from "@/utils/tasks.utils";
import ErrorBoundary from "@/components/ErrorBoundary";
import { AuthProvider, useAuth } from "@/hooks/useAuth";

import {
setJSExceptionHandler,
Expand Down Expand Up @@ -100,17 +101,26 @@ export default function RootLayout() {
return null;
}

return <RootLayoutNav />;
return (
<AuthProvider>
<RootLayoutNav />
</AuthProvider>
);
}

function RootLayoutNav() {
const colorScheme = useColorScheme();
const { user } = useAuth();

return (
<ErrorBoundary>
<ThemeProvider value={colorScheme === "dark" ? DarkTheme : DefaultTheme}>
<Stack>
<Stack.Screen name="(tabs)" options={{ headerShown: false }} />
{user ? (
<Stack.Screen name="(tabs)" options={{ headerShown: false }} />
) : (
<Stack.Screen name="login" options={{ headerShown: false }} />
)}
<Stack.Screen name="modal" options={{ presentation: "modal" }} />
</Stack>
</ThemeProvider>
Expand Down
46 changes: 46 additions & 0 deletions app/login.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import { useEffect } from 'react';
import { View, StyleSheet } from 'react-native';
import { GoogleSignin, GoogleSigninButton } from '@react-native-google-signin/google-signin';
import Constants from 'expo-constants';
import { useAuth } from '@/hooks/useAuth';

export default function LoginScreen() {
const { setUser } = useAuth();

useEffect(() => {
GoogleSignin.configure({
webClientId: Constants.expoConfig?.extra?.googleWebClientId,
});
}, []);

const signIn = async () => {
try {
await GoogleSignin.hasPlayServices({ showPlayServicesUpdateDialog: true });
const result = await GoogleSignin.signIn();
if (result.type === 'success') {
setUser({ idToken: result.data.idToken ?? '', user: result.data.user });
fetch('https://new.codebuilder.org/api/auth/google', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ idToken: result.data.idToken }),
}).catch((e) => console.error('Auth callback error:', e));
}
} catch (e) {
console.error('Google sign in error:', e);
}
};

return (
<View style={styles.container}>
<GoogleSigninButton
onPress={signIn}
size={GoogleSigninButton.Size.Wide}
color={GoogleSigninButton.Color.Dark}
/>
</View>
);
}

const styles = StyleSheet.create({
container: { flex: 1, justifyContent: 'center', alignItems: 'center' },
});
34 changes: 34 additions & 0 deletions hooks/useAuth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { createContext, useContext, useState, ReactNode } from 'react';

export interface AuthUser {
idToken: string;
user: {
id: string;
name: string | null;
email: string;
photo: string | null;
familyName: string | null;
givenName: string | null;
};
}

interface AuthContextType {
user: AuthUser | null;
setUser: (user: AuthUser | null) => void;
}

const AuthContext = createContext<AuthContextType>({
user: null,
setUser: () => {},
});

export const AuthProvider = ({ children }: { children: ReactNode }) => {
const [user, setUser] = useState<AuthUser | null>(null);
return (
<AuthContext.Provider value={{ user, setUser }}>
{children}
</AuthContext.Provider>
);
};

export const useAuth = () => useContext(AuthContext);
17 changes: 17 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
"@react-native-firebase/app": "^22.2.1",
"@react-native-firebase/auth": "^22.2.1",
"@react-native-firebase/messaging": "^22.2.1",
"@react-native-google-signin/google-signin": "^15.0.0",
"@react-navigation/native": "^7.1.6",
"@react-navigation/native-stack": "^7.3.10",
"babel-preset-expo": "~13.0.0",
Expand Down