Closed NoelOsiro closed 2 weeks ago
Using Firebase with Google and Expo is a great choice for this flow, as Firebase provides secure, scalable authentication and works well with Expo for React Native mobile development. Here’s a breakdown of setting up the user registration and login process:
[ ] - In the Firebase console, register your app with the platform you’re using (iOS and/or Android).
In your Expo project, install Firebase and Google authentication packages:
expo install firebase expo-auth-session
The expo-auth-session
package helps with managing authentication redirects for Google Sign-In.
Set up Firebase in your app by creating a firebaseConfig.js
file:
// firebaseConfig.js
import firebase from 'firebase/app';
import 'firebase/auth';
const firebaseConfig = {
apiKey: "YOUR_API_KEY",
authDomain: "YOUR_AUTH_DOMAIN",
projectId: "YOUR_PROJECT_ID",
storageBucket: "YOUR_STORAGE_BUCKET",
messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
appId: "YOUR_APP_ID"
};
if (!firebase.apps.length) {
firebase.initializeApp(firebaseConfig);
}
export { firebase };
In your AuthScreen.js
component, handle email/password sign-up and login:
import React, { useState } from 'react';
import { View, TextInput, Button, Text, Alert } from 'react-native';
import { firebase } from './firebaseConfig';
export default function AuthScreen() {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const handleSignUp = async () => {
try {
await firebase.auth().createUserWithEmailAndPassword(email, password);
Alert.alert("Success", "Account created!");
} catch (error) {
Alert.alert("Error", error.message);
}
};
const handleLogin = async () => {
try {
await firebase.auth().signInWithEmailAndPassword(email, password);
Alert.alert("Success", "Logged in!");
} catch (error) {
Alert.alert("Error", error.message);
}
};
return (
<View>
<TextInput placeholder="Email" onChangeText={setEmail} value={email} />
<TextInput placeholder="Password" onChangeText={setPassword} value={password} secureTextEntry />
<Button title="Sign Up" onPress={handleSignUp} />
<Button title="Log In" onPress={handleLogin} />
</View>
);
}
Use expo-auth-session
to manage Google login redirects.
import * as Google from 'expo-auth-session/providers/google';
import { firebase } from './firebaseConfig';
export default function AuthScreen() {
// Google Sign-In setup
const [request, response, promptAsync] = Google.useIdTokenAuthRequest({
clientId: 'YOUR_GOOGLE_CLIENT_ID',
});
React.useEffect(() => {
if (response?.type === 'success') {
const { id_token } = response.params;
const credential = firebase.auth.GoogleAuthProvider.credential(id_token);
firebase.auth().signInWithCredential(credential);
}
}, [response]);
return (
<View>
<Button
title="Sign In with Google"
disabled={!request}
onPress={() => promptAsync()}
/>
</View>
);
}
On app load, check if a user is already authenticated:
import React, { useEffect, useState } from 'react';
import { firebase } from './firebaseConfig';
export default function App() {
const [user, setUser] = useState(null);
useEffect(() => {
const unsubscribe = firebase.auth().onAuthStateChanged((user) => {
setUser(user);
});
return unsubscribe; // unsubscribe on unmount
}, []);
if (user) {
return <HomeScreen />;
} else {
return <AuthScreen />;
}
}
Add a logout button to allow users to sign out when they choose:
const handleLogout = async () => {
try {
await firebase.auth().signOut();
} catch (error) {
Alert.alert("Error", error.message);
}
};
This setup provides a comprehensive authentication flow using Firebase with email/password and Google authentication in an Expo app. Let me know if you'd like help with handling authentication errors, adding form validation, or any other functionality!
// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
import { getAnalytics } from "firebase/analytics";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries
// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
apiKey: "AIzaSyD8-ba9qXPICD-cFo1WS53OYtRRosVjUAE",
authDomain: "cowtrack-601c1.firebaseapp.com",
projectId: "cowtrack-601c1",
storageBucket: "cowtrack-601c1.appspot.com",
messagingSenderId: "1012437180888",
appId: "1:1012437180888:web:806373b6390821ce7892ad",
measurementId: "G-BTDV6EEC0K"
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);
Goal: Securely log in farmers or farm managers. Process: Farmers can sign up by providing basic details (e.g., name, email, password, and possibly farm details). Social login options like Google or Facebook could also streamline access. Returning users can log in, and sessions can be saved to minimize repeated logins.