wip: almost there, needs dev mode sorted + loading

This commit is contained in:
Loewy 2024-02-07 15:39:11 -08:00
parent 07db6e21db
commit b9221fa949
9 changed files with 130 additions and 112 deletions

39
App.tsx
View File

@ -1,43 +1,14 @@
import React, { useEffect } from "react";
import { ClientProvider, useAuthHeader } from "./src/graphql/client";
import React from "react";
import { AuthProvider } from "./src/context";
import { ClientProvider } from "./src/graphql/client";
import AppNavigator from "./src/navigation/app-navigator";
import { DEV_USER_ID } from "@env";
import AsyncStorage from "@react-native-async-storage/async-storage";
import Loading from "./src/lib/loading";
// TODO: move to different file?
const SetAuthHeaderBasedOnEnv = () => {
const { setAuthHeader } = useAuthHeader();
useEffect(() => {
const setAuthAsync = async () => {
if (DEV_USER_ID) {
console.log("Setting fake authorization user to: ", DEV_USER_ID);
setAuthHeader({ key: "user_id", value: DEV_USER_ID });
} else {
// Fetch token for authenticated users in production
const token = await AsyncStorage.getItem("token"); // get from not firebase auth ASYNC
if (token) {
console.log("Setting firebase auth token");
setAuthHeader({ key: "Authorization", value: `Bearer ${token}` });
}
}
};
setAuthAsync();
}, [setAuthHeader]);
return null;
};
const App: React.FC = () => {
return (
<ClientProvider>
<Loading>
<SetAuthHeaderBasedOnEnv />
<AuthProvider>
<AppNavigator />
</Loading>
</AuthProvider>
</ClientProvider>
);
};

View File

@ -4,7 +4,6 @@
"main": "node_modules/expo/AppEntry.js",
"scripts": {
"start": "NODE_ENV=development && expo start",
"start:test": "NODE_ENV=development && expo start",
"start:android": "expo start --android",
"start:ios": "expo start --ios",
"android": "expo run:android",
@ -12,7 +11,7 @@
"android:test": "node ./start.js test",
"ios": "expo run:ios",
"ios:dev": "NODE_ENV=development expo run:ios",
"ios:prod": "NODE_ENV=production expo run:ios",
"ios:prod": "NODE_ENV=test expo run:ios",
"web": "expo start --web",
"lint": "eslint . --ext .js,.ts,.tsx",
"lint:fix": "eslint . --ext .ts,.tsx --fix",

View File

@ -1,4 +1,3 @@
import AsyncStorage from "@react-native-async-storage/async-storage";
import auth, { FirebaseAuthTypes } from "@react-native-firebase/auth";
import { Alert } from "react-native";
@ -47,7 +46,6 @@ export const getCurrentUserToken = async (): Promise<string | null> => {
return null;
};
export const handleSignOut = async (): Promise<void> => {
await AsyncStorage.removeItem("token");
await auth().signOut();
export const handleSignOut = (): Promise<void> => {
return auth().signOut();
};

View File

@ -1,18 +1,16 @@
import React from "react";
import { Button } from "react-native";
import { handleSignOut } from "../../auth";
import { useAuth } from "../../context";
import { useAuthHeader } from "../../graphql/client";
export default function SignOutButton(): React.JSX.Element {
const { logOut } = useAuth();
const { setAuthHeader } = useAuthHeader();
return (
<Button
title={"Sign out"}
onPress={async () => {
setAuthHeader({ key: "Authorization", value: "" });
await handleSignOut();
}}
/>
);
const handleSignOut = async () => {
await logOut();
setAuthHeader({ key: "Authorization", value: "" });
};
return <Button title={"Sign out"} onPress={handleSignOut} />;
}

View File

@ -0,0 +1,82 @@
import { DEV_USER_ID } from "@env";
import AsyncStorage from "@react-native-async-storage/async-storage";
import { FirebaseAuthTypes } from "@react-native-firebase/auth";
import React, { createContext, useContext, useEffect, useState } from "react";
import { handleSignOut, onAuthStateChanged } from "../auth/firebase-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();
const [user, setUser] = 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)
const authStateChangeCallback = async (user) => {
console.log("user:", user);
if (user) {
const token = await user.getIdToken();
if (token) {
await AsyncStorage.setItem("token", token);
setAuthHeader({ key: "Authorization", value: token });
setUser(user);
setIsLoggedIn(true);
setIsLoading(false)
}
} else {
setIsLoggedIn(false);
}
}
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);
}
};
setAuthAsync();
}, [setAuthHeader]);
useEffect(() => {
let unsubscribe: () => void = () => console.log('Dev mode unsubscribe - really dense fn')
if (!DEV_USER_ID) {
unsubscribe = onAuthStateChanged(authStateChangeCallback);
}
return unsubscribe;
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
const logOut = async () => {
await AsyncStorage.removeItem("token");
await handleSignOut();
};
return (
<AuthContext.Provider value={{ isLoggedIn, isLoading, user, 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;
};

3
src/context/index.ts Normal file
View File

@ -0,0 +1,3 @@
import { AuthProvider, useAuth } from "./auth-context";
export { AuthProvider, useAuth };

View File

@ -6,13 +6,13 @@ import {
import { createNativeStackNavigator } from "@react-navigation/native-stack";
import { useColorScheme } from "react-native";
import { useAuth } from "../context";
import Login from "../screens/login";
import Tabs from "./tab-navigator";
import AsyncStorage from "@react-native-async-storage/async-storage";
const Stack = createNativeStackNavigator();
const ScreensStack = () => (
const AppStack = () => (
<Stack.Navigator>
<Stack.Screen
name="Tabs"
@ -31,18 +31,13 @@ const ScreensStack = () => (
export default function AppNavigator(): React.JSX.Element {
// useColorScheme get's the theme from device settings
const scheme = useColorScheme();
const getToken = async () => {
const token = await AsyncStorage.getItem('token')
console.log('token', token)
return token
}
const { isLoggedIn } = useAuth();
return (
<NavigationContainer theme={scheme === "dark" ? DarkTheme : DefaultTheme}>
<Stack.Navigator screenOptions={{ headerShown: false }}>
{getToken ? (
<Stack.Screen name="App" component={ScreensStack} />
{isLoggedIn ? (
<Stack.Screen name="App" component={AppStack} />
) : (
<Stack.Screen
name="Login"
@ -50,8 +45,6 @@ export default function AppNavigator(): React.JSX.Element {
options={{ headerShown: false }}
/>
)}
</Stack.Navigator>
</NavigationContainer>
);

View File

@ -1,51 +1,24 @@
// Login.tsx
import AsyncStorage from "@react-native-async-storage/async-storage";
import { FirebaseAuthTypes } from "@react-native-firebase/auth";
import React, { useEffect, useState } from "react";
import React, { useState } from "react";
import {
Button,
Keyboard,
Text,
TextInput,
TouchableWithoutFeedback,
View,
} from "react-native";
import {
confirmCode,
handleSignInWithPhoneNumber,
onAuthStateChanged,
} from "../auth";
import SignOutButton from "../component/buttons/sign-out";
import { useAuthHeader } from "../graphql/client";
import { confirmCode, handleSignInWithPhoneNumber } from "../auth";
export default function Login({ navigation }) {
export default function Login() {
const [phoneNumber, setPhoneNumber] = useState<string>("");
const [code, setCode] = useState<string>("");
const [user, setUser] = useState<FirebaseAuthTypes.User | null>(null);
const [confirm, setConfirm] =
useState<FirebaseAuthTypes.ConfirmationResult | null>(null);
const { authHeader, setAuthHeader } = useAuthHeader();
useEffect(() => {
const unsubscribe = onAuthStateChanged(async (user) => {
setUser(user);
if (user) {
const token = await user.getIdToken();
if (token) {
await AsyncStorage.setItem("token", token);
setAuthHeader({ key: "Authorization", value: token });
}
}
});
return unsubscribe;
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
console.log(authHeader.value);
return (
<TouchableWithoutFeedback onPress={() => Keyboard.dismiss()}>
<View style={{ alignItems: "center" }}>
<View style={{ flex: 1, alignItems: "center", justifyContent: "center" }}>
<TextInput
style={{
width: "50%",
@ -86,24 +59,6 @@ export default function Login({ navigation }) {
: confirm && confirmCode(confirm, code)
}
/>
<Text>
{authHeader.key}: {authHeader.value}
</Text>
{user && (
<>
<Text style={{ marginTop: 10 }}>
Display name: {user?.displayName}
</Text>
<Text>Phone number: {user?.phoneNumber}</Text>
<SignOutButton />
<Button
color="orange"
title="Go to app"
onPress={() => navigation.push("Tabs")}
/>
</>
)}
</View>
</TouchableWithoutFeedback>
);

View File

@ -1,14 +1,33 @@
import React from "react";
import { StyleSheet, View } from "react-native";
import { StyleSheet, Text, View } from "react-native";
import { graph_data_two_measures } from "../../test/mock/charts/mock-data";
import SignOutButton from "../component/buttons/sign-out";
import BarGraph from "../component/charts/bar-graph/bar-graph";
import { useAuth } from "../context";
import { useAuthHeader } from "../graphql/client";
// Session Mock - can be used for session summary screen using a query handler component
// BarGraph component using mocked data currently
export default function SessionScreen() {
const { user } = useAuth();
const { authHeader } = useAuthHeader();
return (
<View style={StyleSheet.absoluteFill}>
<BarGraph data={graph_data_two_measures} />
{user && (
<>
<Text style={{ marginTop: 10 }}>
Display name: {user?.displayName}
</Text>
<Text>Phone number: {user?.phoneNumber}</Text>
</>
)}
<SignOutButton />
<Text>
{authHeader.key}: {authHeader.value}
</Text>
</View>
);
}