Skip to content

Commit

Permalink
Persistance enabled for android as well in addition to web
Browse files Browse the repository at this point in the history
  • Loading branch information
ThatNinjaGuy committed Sep 14, 2024
1 parent df2ec06 commit 014d308
Show file tree
Hide file tree
Showing 4 changed files with 151 additions and 33 deletions.
116 changes: 89 additions & 27 deletions components/Authentication/AuthProvider.js
Original file line number Diff line number Diff line change
@@ -1,51 +1,113 @@
import React, { createContext, useState, useEffect } from "react";
import { onAuthStateChanged } from "firebase/auth";
import { auth } from "@/firebase/firebaseConfig";
import { onAuthStateChanged, signInWithCustomToken } from "firebase/auth";
import { auth, db } from "@/firebase/firebaseConfig";
import { collection, getDocs, query, where } from "firebase/firestore";
import { db } from "@/firebase/firebaseConfig";
import AsyncStorage from "@react-native-async-storage/async-storage";
import { Platform } from "react-native";

const AuthContext = createContext();

export const AuthProvider = ({ children }) => {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);

const storeAuthToken = async (user) => {
try {
const token = await user.getIdToken();
if (Platform.OS === "web") {
localStorage.setItem("authToken", token);
} else {
await AsyncStorage.setItem("authToken", token);
}
} catch (error) {
console.error("Error storing auth token:", error);
}
};

const getStoredToken = async () => {
if (Platform.OS === "web") {
return localStorage.getItem("authToken");
} else {
return await AsyncStorage.getItem("authToken");
}
};

const fetchStaffDetails = async (user) => {
try {
const staffsRef = collection(db, "hotel-details/staff-details/staffs");
const q = query(staffsRef, where("authId", "==", user.uid));
const querySnapshot = await getDocs(q);

const staffs = querySnapshot.docs.map((doc) => ({
id: doc.id,
...doc.data(),
}));

if (staffs.length > 0) {
return {
...user,
staffDetails: staffs[0],
};
}
return user;
} catch (error) {
console.error("Error fetching staff details:", error);
return user;
}
};

useEffect(() => {
const subscriber = onAuthStateChanged(auth, async (user) => {
if (user) {
const initializeAuth = async () => {
const token = await getStoredToken();
if (token) {
try {
const staffsRef = collection(
db,
"hotel-details/staff-details/staffs"
);
const q = query(staffsRef, where("authId", "==", user.uid));
const querySnapshot = await getDocs(q);

const staffs = querySnapshot.docs.map((doc) => ({
id: doc.id,
...doc.data(),
}));
if (staffs.length > 0) {
const updatedUser = {
...user,
staffDetails: staffs[0],
};
setUser(updatedUser);
await signInWithCustomToken(auth, token);
} catch (error) {
console.error("Error signing in with stored token:", error);
// Clear invalid token
if (Platform.OS === "web") {
localStorage.removeItem("authToken");
} else {
setUser(user);
await AsyncStorage.removeItem("authToken");
}
} catch (error) {
setUser(user);
}
}
setLoading(false);
};

initializeAuth();

const subscriber = onAuthStateChanged(auth, async (firebaseUser) => {
if (firebaseUser) {
const updatedUser = await fetchStaffDetails(firebaseUser);
setUser(updatedUser);
await storeAuthToken(firebaseUser);
} else {
setUser(user);
setUser(null);
}
});

return () => subscriber();
}, []);

const logout = async () => {
await auth.signOut();
if (Platform.OS === "web") {
localStorage.removeItem("authToken");
} else {
await AsyncStorage.removeItem("authToken");
}
setUser(null);
};

if (loading) {
return null; // or a loading component
}

return (
<AuthContext.Provider value={{ user }}>{children}</AuthContext.Provider>
<AuthContext.Provider value={{ user, logout }}>
{children}
</AuthContext.Provider>
);
};

Expand Down
27 changes: 24 additions & 3 deletions firebase/firebaseConfig.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
import { initializeApp } from "firebase/app";
import { initializeFirestore } from "firebase/firestore";
import { getAuth } from "firebase/auth";
import {
getAuth,
initializeAuth,
getReactNativePersistence,
} from "firebase/auth";
import AsyncStorage from "@react-native-async-storage/async-storage";
import { Platform } from "react-native";

const firebaseConfig = {
apiKey: "AIzaSyAN-nxJtF6ROGWMjLboI4dEBKDNGnsMIWg",
Expand All @@ -14,11 +20,26 @@ const firebaseConfig = {

const app = initializeApp(firebaseConfig);

const auth = getAuth(app);
let auth;

if (Platform.OS === "web") {
auth = getAuth(app);
// Set persistence for web
import("firebase/auth").then(
({ browserLocalPersistence, setPersistence }) => {
setPersistence(auth, browserLocalPersistence);
}
);
} else {
// Initialize auth with AsyncStorage persistence for React Native
auth = initializeAuth(app, {
persistence: getReactNativePersistence(AsyncStorage),
});
}

// Initialize Firestore with persistent local cache
const db = initializeFirestore(app, {
experimentalForceLongPolling: true, // Optional: Use if you face network issues
experimentalForceLongPolling: true,
synchronizeTabs: true,
});

Expand Down
34 changes: 34 additions & 0 deletions package-lock.json

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

7 changes: 4 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
"@dotlottie/react-player": "^1.6.19",
"@expo/metro-config": "^0.18.9",
"@expo/vector-icons": "^14.0.2",
"@react-native-async-storage/async-storage": "^1.24.0",
"@react-native-community/datetimepicker": "github:react-native-community/datetimepicker",
"@react-native-firebase/app": "^20.4.0",
"@react-native-firebase/auth": "^20.4.0",
Expand All @@ -26,9 +27,11 @@
"@react-navigation/drawer": "^6.7.2",
"@react-navigation/native": "^6.1.18",
"expo": "~51.0.20",
"expo-blur": "~13.0.2",
"expo-constants": "~16.0.2",
"expo-file-system": "~17.0.1",
"expo-font": "~12.0.8",
"expo-linear-gradient": "~13.0.2",
"expo-linking": "~6.3.1",
"expo-print": "~13.0.1",
"expo-router": "~3.5.18",
Expand Down Expand Up @@ -60,9 +63,7 @@
"react-native-super-grid": "^6.0.1",
"react-native-toast-message": "^2.2.0",
"react-native-vector-icons": "^10.1.0",
"react-native-web": "^0.19.12",
"expo-linear-gradient": "~13.0.2",
"expo-blur": "~13.0.2"
"react-native-web": "^0.19.12"
},
"devDependencies": {
"@babel/core": "^7.20.0",
Expand Down

0 comments on commit 014d308

Please sign in to comment.