wip: connect firebase token to apollo headers

This commit is contained in:
Loewy 2024-02-05 22:50:24 -08:00
parent 01f1f94dd6
commit 6bfd0621ad
6 changed files with 114 additions and 69 deletions

26
App.tsx
View File

@ -1,16 +1,30 @@
import { DEV_USER_ID } from "@env"; import { DEV_USER_ID } from "@env";
import React from "react"; import React, { useEffect } from "react";
import { ClientProvider, useAuthHeader } from "./graphql/client"; import { ClientProvider, useAuthHeader } from "./graphql/client";
import AppNavigator from "./navigation/app-navigator"; import AppNavigator from "./navigation/app-navigator";
import { getCurrentUserToken } from "./auth";
// TODO: can be done when we go with a src top level directory -- should live on cofig
const SetAuthHeaderBasedOnEnv = () => { const SetAuthHeaderBasedOnEnv = () => {
const { setAuthHeader } = useAuthHeader(); const { setAuthHeader } = useAuthHeader();
React.useEffect(() => {
if (DEV_USER_ID) { useEffect(() => {
console.log("Setting fake authorization user to: ", DEV_USER_ID); const setAuthAsync = async () => {
setAuthHeader({ key: "user_id", value: DEV_USER_ID }); // 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 getCurrentUserToken();
if (token) {
console.log("Setting firebase auth token");
setAuthHeader({ key: "Authorization", value: `Bearer ${token}` });
}
// }
};
setAuthAsync();
}, [setAuthHeader]); }, [setAuthHeader]);
return null; return null;

48
auth/firebase-auth.tsx Normal file
View File

@ -0,0 +1,48 @@
import auth, { FirebaseAuthTypes } from '@react-native-firebase/auth';
import { Alert } from 'react-native';
export const signInWithPhoneNumber = async (phoneNumber: string): Promise<FirebaseAuthTypes.ConfirmationResult | undefined> => {
if (!phoneNumber) {
Alert.alert("Please enter a valid phone number with a country code");
return;
}
try {
const confirmation = await auth().signInWithPhoneNumber(phoneNumber);
return confirmation;
} catch (err) {
console.warn(err);
Alert.alert("There was an error. Make sure you are using a country code (ex: +1 for US)");
}
};
export const confirmCode = async (confirm: FirebaseAuthTypes.ConfirmationResult, code: string): Promise<void> => {
try {
await confirm.confirm(code);
} catch {
Alert.alert("Invalid code, please try again.");
}
};
export const onAuthStateChanged = (callback: (user: FirebaseAuthTypes.User | null) => void) => {
return auth().onAuthStateChanged(callback);
};
export const getCurrentUserToken = async (): Promise<string | null> => {
const user = auth().currentUser;
if (user) {
return await user.getIdToken();
}
return null;
};
export const signOut = async (): Promise<void> => {
try {
auth().signOut()
// tie in to AppNav
} catch (err) {
console.error(err)
// toggle appnav state regardless
// Handle sign out error - have to look into best way to do this - asyncstorage?
}
}

15
auth/index.ts Normal file
View File

@ -0,0 +1,15 @@
import {
signInWithPhoneNumber,
confirmCode,
onAuthStateChanged,
getCurrentUserToken,
signOut
} from './firebase-auth'
export {
signInWithPhoneNumber,
confirmCode,
onAuthStateChanged,
getCurrentUserToken,
signOut
}

View File

@ -14,13 +14,13 @@ const Stack = createNativeStackNavigator();
const ScreensStack = () => ( const ScreensStack = () => (
<Stack.Navigator> <Stack.Navigator>
<Stack.Screen <Stack.Screen
name="Tabs" name="Login"
component={Tabs} component={Login}
options={{ headerShown: false }} options={{ headerShown: false }}
/> />
<Stack.Screen <Stack.Screen
name="Login" name="Tabs"
component={Login} component={Tabs}
options={{ headerShown: false }} options={{ headerShown: false }}
/> />
</Stack.Navigator> </Stack.Navigator>

View File

@ -7,7 +7,9 @@
"start:android": "expo start --android", "start:android": "expo start --android",
"start:ios": "expo start --ios", "start:ios": "expo start --ios",
"android": "expo run:android", "android": "expo run:android",
"android:prod": "cp .env.production .env && cat .env && NODE_ENV=production expo run:android",
"ios": "expo run:ios", "ios": "expo run:ios",
"ios:prod": "cp .env.production .env && expo run:ios",
"web": "expo start --web", "web": "expo start --web",
"lint": "eslint . --ext .js,.ts,.tsx", "lint": "eslint . --ext .js,.ts,.tsx",
"lint:fix": "eslint . --ext .ts,.tsx --fix", "lint:fix": "eslint . --ext .ts,.tsx --fix",

View File

@ -1,72 +1,34 @@
import auth, { FirebaseAuthTypes } from "@react-native-firebase/auth"; // Login.tsx
import React, { useEffect, useState } from "react"; import React, { useEffect, useState } from 'react';
import { import {
Alert,
Button, Button,
Keyboard, Keyboard,
Text, Text,
TextInput, TextInput,
TouchableWithoutFeedback, TouchableWithoutFeedback,
View, View,
} from "react-native"; } from 'react-native';
import { signInWithPhoneNumber, confirmCode, onAuthStateChanged, signOut } from '../auth'; // Adjust the path as necessary
// This code is beginning of Auth Implementation - actual implementation will differ and involve more UI import { FirebaseAuthTypes } from '@react-native-firebase/auth';
// Does not have a restart or proper handling of code confirmation, should only be used for obtaining token/testing import { useAuthHeader } from '../graphql/client';
// Currently working for Android builds, iOS has open issue #56
export default function Login() { export default function Login() {
const [phoneNumber, setPhoneNumber] = useState<string>(""); const [phoneNumber, setPhoneNumber] = useState<string>('');
const [code, setCode] = useState<string>(""); const [code, setCode] = useState<string>('');
const [user, setUser] = useState<FirebaseAuthTypes.User | null>(null);
const [user, setUser] = useState(null); const [confirm, setConfirm] = useState<FirebaseAuthTypes.ConfirmationResult | null>(null);
const [confirm, setConfirm] = const authHeader = useAuthHeader()
useState<FirebaseAuthTypes.ConfirmationResult | null>(null);
async function onAuthStateChanged(user: any) {
setUser(user);
if (user) {
// eslint-disable-next-line no-unused-vars, @typescript-eslint/no-unused-vars
const token = await auth().currentUser?.getIdToken();
// To debug/check token & user return, use these logs
// console.log(token) // token log
// console.log(user) // user log
}
}
async function signInWithPhoneNumber(phoneNumber: string) {
if (!phoneNumber) {
return Alert.alert(
"Please enter a valid phone number with a country code",
);
}
try {
const confirmation = await auth().signInWithPhoneNumber(phoneNumber);
setConfirm(confirmation);
} catch (err) {
// TODO: implement more robust error handling by parsing err message
console.warn(err);
Alert.alert(
"There was an error. Make sure you are using a country code (ex: +1 for US)",
);
}
}
async function confirmCode() {
try {
await confirm?.confirm(code);
} catch {
Alert.alert("Invalid code, please try again.");
}
}
useEffect(() => { useEffect(() => {
const subscriber = auth().onAuthStateChanged(onAuthStateChanged); const subscriber = onAuthStateChanged(setUser);
return subscriber; return subscriber; // This may need adjustment based on your specific implementation
}, []); }, []);
return ( return (
<TouchableWithoutFeedback onPress={() => Keyboard.dismiss()}> <TouchableWithoutFeedback onPress={() => Keyboard.dismiss()}>
<View style={{ alignItems: "center" }}> <View style={{ alignItems: 'center' }}>
<TextInput <TextInput
style={{ style={{
width: "50%", width: "50%",
@ -100,17 +62,21 @@ export default function Login() {
/> />
)} )}
<Button <Button
title={!confirm ? "Receive code" : "Confirm code"} title={!confirm ? 'Receive code' : 'Confirm code'}
onPress={() => onPress={() => !confirm ? signInWithPhoneNumber(phoneNumber).then(setConfirm) : confirm && confirmCode(confirm, code)}
!confirm ? signInWithPhoneNumber(phoneNumber) : confirmCode()
}
/> />
<Text>{authHeader.authHeader.key}: {authHeader.authHeader.value}</Text>
{user && ( {user && (
<> <>
<Text style={{ marginTop: 10 }}> <Text style={{ marginTop: 10 }}>
Display name: {user?.displayName} Display name: {user?.displayName}
</Text> </Text>
<Text>Phone number: {user?.phoneNumber}</Text> <Text>Phone number: {user?.phoneNumber}</Text>
<Button
title={'Sign out'}
onPress={() => signOut()}
/>
</> </>
)} )}
</View> </View>