wip: connect firebase token to apollo headers
This commit is contained in:
parent
01f1f94dd6
commit
6bfd0621ad
26
App.tsx
26
App.tsx
@ -1,16 +1,30 @@
|
||||
import { DEV_USER_ID } from "@env";
|
||||
import React from "react";
|
||||
import React, { useEffect } from "react";
|
||||
import { ClientProvider, useAuthHeader } from "./graphql/client";
|
||||
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 { setAuthHeader } = useAuthHeader();
|
||||
|
||||
React.useEffect(() => {
|
||||
if (DEV_USER_ID) {
|
||||
console.log("Setting fake authorization user to: ", DEV_USER_ID);
|
||||
setAuthHeader({ key: "user_id", value: DEV_USER_ID });
|
||||
}
|
||||
|
||||
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 getCurrentUserToken();
|
||||
if (token) {
|
||||
console.log("Setting firebase auth token");
|
||||
setAuthHeader({ key: "Authorization", value: `Bearer ${token}` });
|
||||
}
|
||||
// }
|
||||
};
|
||||
|
||||
setAuthAsync();
|
||||
}, [setAuthHeader]);
|
||||
|
||||
return null;
|
||||
|
48
auth/firebase-auth.tsx
Normal file
48
auth/firebase-auth.tsx
Normal 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
15
auth/index.ts
Normal file
@ -0,0 +1,15 @@
|
||||
import {
|
||||
signInWithPhoneNumber,
|
||||
confirmCode,
|
||||
onAuthStateChanged,
|
||||
getCurrentUserToken,
|
||||
signOut
|
||||
} from './firebase-auth'
|
||||
|
||||
export {
|
||||
signInWithPhoneNumber,
|
||||
confirmCode,
|
||||
onAuthStateChanged,
|
||||
getCurrentUserToken,
|
||||
signOut
|
||||
}
|
@ -14,13 +14,13 @@ const Stack = createNativeStackNavigator();
|
||||
const ScreensStack = () => (
|
||||
<Stack.Navigator>
|
||||
<Stack.Screen
|
||||
name="Tabs"
|
||||
component={Tabs}
|
||||
name="Login"
|
||||
component={Login}
|
||||
options={{ headerShown: false }}
|
||||
/>
|
||||
<Stack.Screen
|
||||
name="Login"
|
||||
component={Login}
|
||||
name="Tabs"
|
||||
component={Tabs}
|
||||
options={{ headerShown: false }}
|
||||
/>
|
||||
</Stack.Navigator>
|
||||
|
@ -7,7 +7,9 @@
|
||||
"start:android": "expo start --android",
|
||||
"start:ios": "expo start --ios",
|
||||
"android": "expo run:android",
|
||||
"android:prod": "cp .env.production .env && cat .env && NODE_ENV=production expo run:android",
|
||||
"ios": "expo run:ios",
|
||||
"ios:prod": "cp .env.production .env && expo run:ios",
|
||||
"web": "expo start --web",
|
||||
"lint": "eslint . --ext .js,.ts,.tsx",
|
||||
"lint:fix": "eslint . --ext .ts,.tsx --fix",
|
||||
@ -83,4 +85,4 @@
|
||||
"@babel/core": "^7.20.2",
|
||||
"babel-loader": "^8.3.0"
|
||||
}
|
||||
}
|
||||
}
|
@ -1,72 +1,34 @@
|
||||
import auth, { FirebaseAuthTypes } from "@react-native-firebase/auth";
|
||||
import React, { useEffect, useState } from "react";
|
||||
// Login.tsx
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import {
|
||||
Alert,
|
||||
Button,
|
||||
Keyboard,
|
||||
Text,
|
||||
TextInput,
|
||||
TouchableWithoutFeedback,
|
||||
View,
|
||||
} from "react-native";
|
||||
|
||||
// This code is beginning of Auth Implementation - actual implementation will differ and involve more UI
|
||||
// Does not have a restart or proper handling of code confirmation, should only be used for obtaining token/testing
|
||||
// Currently working for Android builds, iOS has open issue #56
|
||||
} from 'react-native';
|
||||
import { signInWithPhoneNumber, confirmCode, onAuthStateChanged, signOut } from '../auth'; // Adjust the path as necessary
|
||||
import { FirebaseAuthTypes } from '@react-native-firebase/auth';
|
||||
import { useAuthHeader } from '../graphql/client';
|
||||
|
||||
export default function Login() {
|
||||
const [phoneNumber, setPhoneNumber] = useState<string>("");
|
||||
const [code, setCode] = useState<string>("");
|
||||
|
||||
const [user, setUser] = useState(null);
|
||||
const [confirm, setConfirm] =
|
||||
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.");
|
||||
}
|
||||
}
|
||||
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 = useAuthHeader()
|
||||
|
||||
useEffect(() => {
|
||||
const subscriber = auth().onAuthStateChanged(onAuthStateChanged);
|
||||
return subscriber;
|
||||
const subscriber = onAuthStateChanged(setUser);
|
||||
return subscriber; // This may need adjustment based on your specific implementation
|
||||
}, []);
|
||||
|
||||
|
||||
|
||||
return (
|
||||
<TouchableWithoutFeedback onPress={() => Keyboard.dismiss()}>
|
||||
<View style={{ alignItems: "center" }}>
|
||||
<View style={{ alignItems: 'center' }}>
|
||||
<TextInput
|
||||
style={{
|
||||
width: "50%",
|
||||
@ -100,17 +62,21 @@ export default function Login() {
|
||||
/>
|
||||
)}
|
||||
<Button
|
||||
title={!confirm ? "Receive code" : "Confirm code"}
|
||||
onPress={() =>
|
||||
!confirm ? signInWithPhoneNumber(phoneNumber) : confirmCode()
|
||||
}
|
||||
title={!confirm ? 'Receive code' : 'Confirm code'}
|
||||
onPress={() => !confirm ? signInWithPhoneNumber(phoneNumber).then(setConfirm) : confirm && confirmCode(confirm, code)}
|
||||
/>
|
||||
<Text>{authHeader.authHeader.key}: {authHeader.authHeader.value}</Text>
|
||||
{user && (
|
||||
<>
|
||||
<Text style={{ marginTop: 10 }}>
|
||||
Display name: {user?.displayName}
|
||||
</Text>
|
||||
<Text>Phone number: {user?.phoneNumber}</Text>
|
||||
|
||||
<Button
|
||||
title={'Sign out'}
|
||||
onPress={() => signOut()}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</View>
|
||||
|
Loading…
Reference in New Issue
Block a user