auth with handler
This commit is contained in:
45
app/AuthHandler.tsx
Normal file
45
app/AuthHandler.tsx
Normal file
@@ -0,0 +1,45 @@
|
||||
import { useRouter, useSegments } from "expo-router";
|
||||
import { onAuthStateChanged } from "firebase/auth";
|
||||
import { doc, getDoc } from "firebase/firestore";
|
||||
import { useEffect } from "react";
|
||||
import { auth, db } from "../firebase_config";
|
||||
import { useUser } from "./ContextUser";
|
||||
|
||||
export function useAuthHandler() {
|
||||
const router = useRouter();
|
||||
const segments = useSegments();
|
||||
const { setUser, setRole } = useUser();
|
||||
|
||||
useEffect(() => {
|
||||
const unsubscribe = onAuthStateChanged(auth, async (currentUser) => {
|
||||
if (!currentUser) {
|
||||
setUser(null);
|
||||
setRole(null);
|
||||
router.replace("/login/login");
|
||||
return;
|
||||
}
|
||||
|
||||
const userDocRef = doc(db, "user", currentUser.uid);
|
||||
const userDoc = await getDoc(userDocRef);
|
||||
|
||||
if (!userDoc.exists()) {
|
||||
setUser(null);
|
||||
setRole(null);
|
||||
router.replace("/login/login");
|
||||
return;
|
||||
}
|
||||
|
||||
const { role } = userDoc.data();
|
||||
setUser(currentUser);
|
||||
setRole(role);
|
||||
|
||||
// Only redirect if we're on login page
|
||||
const inAuthGroup = segments[0] === 'login';
|
||||
if (inAuthGroup) {
|
||||
router.replace("/(tabs)/home");
|
||||
}
|
||||
});
|
||||
|
||||
return unsubscribe;
|
||||
}, []);
|
||||
}
|
||||
Reference in New Issue
Block a user