Files
IWD2-03/INFO-3173 Mobile Development 1/Labs/Lab 5/firebase-DB/App.js
T
2026-10-30 16:32:34 -04:00

310 lines
8.3 KiB
JavaScript

import { StatusBar } from "expo-status-bar";
import React, { useState, useEffect } from "react";
import { View, TextInput, Text, Button, Alert, StyleSheet } from "react-native";
import { db, firestore, auth } from "./FirebaseConfig";
import {
createUserWithEmailAndPassword,
signOut,
signInWithEmailAndPassword,
onAuthStateChanged,
} from "firebase/auth";
import { ref, set, onValue } from "firebase/database";
import { doc, setDoc, onSnapshot } from "firebase/firestore";
export default function App() {
const [registrationEmail, setRegistrationEmail] = useState("");
const [registrationPassword, setRegistrationPassword] = useState("");
const [loginEmail, setLoginEmail] = useState("");
const [loginPassword, setLoginPassword] = useState("");
const [loggedIn, setLoggedIn] = useState(false);
const [databaseData, setDatabaseData] = useState("");
const [user, setUser] = useState(null);
// Monitor authentication state
useEffect(() => {
const unsubscribe = onAuthStateChanged(auth, (currentUser) => {
setUser(currentUser);
setLoggedIn(!!currentUser);
});
return () => unsubscribe();
}, []);
const registerWithFirebase = () => {
if (registrationEmail.length < 4) {
Alert.alert("Please enter an email address.");
return;
}
if (registrationPassword.length < 4) {
Alert.alert("Please enter a password.");
return;
}
createUserWithEmailAndPassword(
auth,
registrationEmail,
registrationPassword
)
.then((userCredential) => {
Alert.alert("User registered successfully!");
setRegistrationEmail("");
setRegistrationPassword("");
})
.catch((error) => {
console.log("Registration error:", error);
if (error.code === "auth/weak-password") {
Alert.alert("The password is too weak.");
} else if (error.code === "auth/email-already-in-use") {
Alert.alert("This email is already registered.");
} else {
Alert.alert(error.message);
}
});
};
const loginWithFirebase = () => {
if (loginEmail.length < 4) {
Alert.alert("Please enter an email address.");
return;
}
if (loginPassword.length < 4) {
Alert.alert("Please enter a password.");
return;
}
signInWithEmailAndPassword(auth, loginEmail, loginPassword)
.then((userCredential) => {
Alert.alert("User logged in successfully!");
setLoginEmail("");
setLoginPassword("");
})
.catch((error) => {
console.log("Login error:", error);
if (error.code === "auth/wrong-password") {
Alert.alert("Wrong password.");
} else if (error.code === "auth/user-not-found") {
Alert.alert("User not found.");
} else {
Alert.alert(error.message);
}
});
};
const signoutWithFirebase = () => {
signOut(auth)
.then(() => {
Alert.alert("User was logged out!");
setDatabaseData("");
})
.catch((error) => {
Alert.alert("Error signing out:", error.message);
});
};
const saveDataWithFirebase = () => {
if (!user) {
Alert.alert("Please log in first.");
return;
}
const userID = user.uid;
// Save to Realtime DB
set(ref(db, "users/" + userID), {
text: databaseData,
timestamp: Date.now(),
})
.then(() => {
console.log("Data saved to Realtime DB");
})
.catch((error) => {
console.log("Realtime DB error:", error);
});
// Save to Firestore
setDoc(
doc(firestore, "users", userID),
{
text: databaseData,
timestamp: Date.now(),
},
{ merge: true }
)
.then(() => {
Alert.alert("Data saved successfully!");
})
.catch((error) => {
Alert.alert("Error saving data");
console.log("Firestore error:", error);
});
};
const retrieveDataWithFirebase = () => {
if (!user) {
Alert.alert("Please log in first.");
return;
}
const userID = user.uid;
const dbRef = ref(db, "users/" + userID);
// Using Realtime DB
onValue(dbRef, (snapshot) => {
if (snapshot.exists()) {
const data = snapshot.val();
setDatabaseData(data.text || "");
Alert.alert("Data retrieved from Realtime DB");
} else {
Alert.alert("No data found");
}
});
// Uncomment for Firestore
/*
const unsubscribe = onSnapshot(doc(firestore, "users", userID), (doc) => {
if (doc.exists()) {
const data = doc.data();
setDatabaseData(data.text || "");
Alert.alert("Data retrieved from Firestore");
} else {
Alert.alert("No data found in Firestore");
}
});
*/
};
return (
<View style={styles.form}>
<StatusBar style="auto" />
{!loggedIn ? (
<View>
<View style={styles.section}>
<Text style={styles.label}>Lab 5 - l_mclean215318</Text>
<Text style={styles.label}>Register with Firebase</Text>
<TextInput
style={styles.textInput}
onChangeText={setRegistrationEmail}
value={registrationEmail}
autoCapitalize="none"
autoCorrect={false}
autoCompleteType="email"
keyboardType="email-address"
placeholder="Email"
/>
<TextInput
style={styles.textInput}
onChangeText={setRegistrationPassword}
value={registrationPassword}
autoCapitalize="none"
autoCorrect={false}
autoCompleteType="password"
placeholder="Password"
secureTextEntry={true}
/>
<Button title="Register" onPress={registerWithFirebase} />
</View>
<View style={styles.section}>
<Text style={styles.label}>Sign In with Firebase</Text>
<TextInput
style={styles.textInput}
onChangeText={setLoginEmail}
value={loginEmail}
autoCapitalize="none"
autoCorrect={false}
autoCompleteType="email"
keyboardType="email-address"
placeholder="Email"
/>
<TextInput
style={styles.textInput}
onChangeText={setLoginPassword}
value={loginPassword}
autoCapitalize="none"
autoCorrect={false}
autoCompleteType="password"
placeholder="Password"
secureTextEntry={true}
/>
<Button title="Login" onPress={loginWithFirebase} />
</View>
</View>
) : (
<View>
<Text style={styles.welcome}>Welcome, {user?.email}</Text>
<TextInput
style={styles.textArea}
multiline={true}
numberOfLines={4}
onChangeText={setDatabaseData}
value={databaseData}
placeholder="Enter your data here..."
/>
<View style={styles.buttonContainer}>
<Button title="Save Data" onPress={saveDataWithFirebase} />
<Button title="Load Data" onPress={retrieveDataWithFirebase} />
</View>
<View style={styles.signOutButton}>
<Button
title="Sign Out"
onPress={signoutWithFirebase}
color="#ff4444"
/>
</View>
</View>
)}
</View>
);
}
const styles = StyleSheet.create({
form: {
flex: 1,
margin: 30,
marginTop: 60,
},
section: {
marginBottom: 30,
},
label: {
fontSize: 18,
marginBottom: 15,
textAlign: "center",
fontWeight: "bold",
},
welcome: {
fontSize: 18,
marginBottom: 20,
textAlign: "center",
fontWeight: "bold",
},
textInput: {
borderColor: "#ccc",
borderWidth: 1,
marginBottom: 15,
paddingVertical: 8,
paddingHorizontal: 10,
borderRadius: 5,
},
textArea: {
borderColor: "#ccc",
borderWidth: 1,
marginBottom: 15,
paddingVertical: 8,
paddingHorizontal: 10,
borderRadius: 5,
height: 100,
textAlignVertical: "top",
},
buttonContainer: {
flexDirection: "row",
justifyContent: "space-between",
marginBottom: 20,
},
signOutButton: {
marginTop: 20,
},
});