railbird-gql/src/context/auth-context.tsx

93 lines
2.4 KiB
TypeScript
Raw Normal View History

import { DEV_USER_ID } from "@env";
import { FirebaseAuthTypes } from "@react-native-firebase/auth";
import React, { createContext, useContext, useEffect, useState } from "react";
2024-02-07 16:59:11 -08:00
import { currentUser, handleSignOut, onAuthStateChanged } from "../auth";
import { useAuthHeader } from "../graphql/client";
interface AuthContextType {
isLoggedIn: boolean;
isLoading: boolean;
user: FirebaseAuthTypes.User | null;
logOut: () => Promise<void>;
}
const AuthContext = createContext<AuthContextType | undefined>(undefined);
export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({
children,
}) => {
const { setAuthHeader } = useAuthHeader();
2024-02-07 16:59:11 -08:00
const [contextUser, setContextUser] = useState<FirebaseAuthTypes.User | null>(
null,
);
const [isLoggedIn, setIsLoggedIn] = useState<boolean>(false);
const [isLoading, setIsLoading] = useState<boolean>(true); // this is for a LoadingContext (auth, app reloads, foreground etc)
2024-02-07 16:59:11 -08:00
const _completeAuthentication = (
user: FirebaseAuthTypes.User,
token: string,
isLoggedIn: boolean,
) => {
setAuthHeader({ key: "Authorization", value: token });
setContextUser(user);
setIsLoggedIn(isLoggedIn);
setIsLoading(false);
};
const authStateChangeCallback = async (user: FirebaseAuthTypes.User) => {
if (user) {
const token = await user.getIdToken();
2024-02-07 16:59:11 -08:00
_completeAuthentication(user, token, true);
} else {
2024-02-07 16:59:11 -08:00
_completeAuthentication(undefined, undefined, false);
}
};
useEffect(() => {
let unsubscribe = () => {
console.log("Dev mode unsubscribe - really dense fn");
};
if (!DEV_USER_ID) {
unsubscribe = onAuthStateChanged(authStateChangeCallback);
}
2024-02-07 16:59:11 -08:00
return unsubscribe;
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
useEffect(() => {
const setAuthAsync = async () => {
console.log("running");
if (DEV_USER_ID) {
console.log("Setting fake authorization user to: ", DEV_USER_ID);
setAuthHeader({ key: "user_id", value: DEV_USER_ID });
setIsLoggedIn(true);
setIsLoading(false);
2024-02-07 16:59:11 -08:00
}
};
setAuthAsync();
}, [setAuthHeader]);
const logOut = async () => {
await handleSignOut();
};
return (
2024-02-07 16:59:11 -08:00
<AuthContext.Provider
value={{ isLoggedIn, isLoading, user: contextUser, logOut }}
>
{children}
</AuthContext.Provider>
);
};
export const useAuth = () => {
const context = useContext(AuthContext);
if (context === undefined) {
throw new Error("useAuth must be used within an AuthProvider");
}
return context;
};