Merge pull request 'Pass firebase token to headers / signOut' (#98) from loewy/firebase-token-headers into master
Reviewed-on: railbird/railbird-mobile#98
This commit is contained in:
commit
4a5dd47bc0
20
App.tsx
20
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 { DEV_USER_ID } from "@env";
|
||||
import AsyncStorage from "@react-native-async-storage/async-storage";
|
||||
|
||||
// TODO: move to different file?
|
||||
const SetAuthHeaderBasedOnEnv = () => {
|
||||
const { setAuthHeader } = useAuthHeader();
|
||||
|
||||
React.useEffect(() => {
|
||||
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;
|
||||
|
53
auth/firebase-auth.tsx
Normal file
53
auth/firebase-auth.tsx
Normal file
@ -0,0 +1,53 @@
|
||||
import AsyncStorage from "@react-native-async-storage/async-storage";
|
||||
import auth, { FirebaseAuthTypes } from "@react-native-firebase/auth";
|
||||
import { Alert } from "react-native";
|
||||
|
||||
export const handleSignInWithPhoneNumber = 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 = (
|
||||
// TODO: eslint not detecting ts?
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
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 handleSignOut = async (): Promise<void> => {
|
||||
await AsyncStorage.removeItem("token");
|
||||
await auth().signOut();
|
||||
};
|
15
auth/index.ts
Normal file
15
auth/index.ts
Normal file
@ -0,0 +1,15 @@
|
||||
import {
|
||||
confirmCode,
|
||||
getCurrentUserToken,
|
||||
handleSignInWithPhoneNumber,
|
||||
handleSignOut,
|
||||
onAuthStateChanged,
|
||||
} from "./firebase-auth";
|
||||
|
||||
export {
|
||||
confirmCode,
|
||||
getCurrentUserToken,
|
||||
handleSignInWithPhoneNumber,
|
||||
handleSignOut,
|
||||
onAuthStateChanged,
|
||||
};
|
18
component/buttons/sign-out.tsx
Normal file
18
component/buttons/sign-out.tsx
Normal file
@ -0,0 +1,18 @@
|
||||
import React from "react";
|
||||
import { Button } from "react-native";
|
||||
import { handleSignOut } from "../../auth";
|
||||
import { useAuthHeader } from "../../graphql/client";
|
||||
|
||||
export default function SignOutButton(): React.JSX.Element {
|
||||
const { setAuthHeader } = useAuthHeader();
|
||||
|
||||
return (
|
||||
<Button
|
||||
title={"Sign out"}
|
||||
onPress={async () => {
|
||||
setAuthHeader({ key: "Authorization", value: "" });
|
||||
await handleSignOut();
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
@ -6,7 +6,7 @@ import {
|
||||
InMemoryCache,
|
||||
from,
|
||||
} from "@apollo/client";
|
||||
import { API_URI } from "@env";
|
||||
|
||||
import React, {
|
||||
ReactNode,
|
||||
createContext,
|
||||
@ -15,6 +15,8 @@ import React, {
|
||||
useState,
|
||||
} from "react";
|
||||
|
||||
import { API_URI } from "@env";
|
||||
|
||||
type Props = {
|
||||
children: ReactNode;
|
||||
};
|
||||
|
@ -3,11 +3,15 @@
|
||||
"version": "1.0.0",
|
||||
"main": "node_modules/expo/AppEntry.js",
|
||||
"scripts": {
|
||||
"start": "cp .env.development .env && expo start",
|
||||
"start": "NODE_ENV=development && expo start",
|
||||
"start:android": "expo start --android",
|
||||
"start:ios": "expo start --ios",
|
||||
"android": "expo run:android",
|
||||
"android:dev": "NODE_ENV=development expo run:android",
|
||||
"android:prod": "NODE_ENV=production expo run:android",
|
||||
"ios": "expo run:ios",
|
||||
"ios:dev": "NODE_ENV=development expo run:ios",
|
||||
"ios:prod": "NODE_ENV=production expo run:ios",
|
||||
"web": "expo start --web",
|
||||
"lint": "eslint . --ext .js,.ts,.tsx",
|
||||
"lint:fix": "eslint . --ext .ts,.tsx --fix",
|
||||
@ -21,6 +25,7 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@apollo/client": "^3.8.8",
|
||||
"@react-native-async-storage/async-storage": "^1.21.0",
|
||||
"@react-native-camera-roll/camera-roll": "^7.4.0",
|
||||
"@react-native-firebase/app": "^18.8.0",
|
||||
"@react-native-firebase/auth": "^18.8.0",
|
||||
|
@ -1,7 +1,8 @@
|
||||
import auth, { FirebaseAuthTypes } from "@react-native-firebase/auth";
|
||||
// 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 {
|
||||
Alert,
|
||||
Button,
|
||||
Keyboard,
|
||||
Text,
|
||||
@ -9,61 +10,39 @@ import {
|
||||
TouchableWithoutFeedback,
|
||||
View,
|
||||
} from "react-native";
|
||||
import {
|
||||
confirmCode,
|
||||
handleSignInWithPhoneNumber,
|
||||
onAuthStateChanged,
|
||||
} from "../auth";
|
||||
import SignOutButton from "../component/buttons/sign-out";
|
||||
import { useAuthHeader } from "../graphql/client";
|
||||
|
||||
// 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
|
||||
|
||||
export default function Login() {
|
||||
export default function Login({ navigation }) {
|
||||
const [phoneNumber, setPhoneNumber] = useState<string>("");
|
||||
const [code, setCode] = useState<string>("");
|
||||
|
||||
const [user, setUser] = useState(null);
|
||||
const [user, setUser] = useState<FirebaseAuthTypes.User | null>(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 { authHeader, setAuthHeader } = useAuthHeader();
|
||||
|
||||
useEffect(() => {
|
||||
const subscriber = auth().onAuthStateChanged(onAuthStateChanged);
|
||||
return subscriber;
|
||||
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" }}>
|
||||
@ -102,15 +81,27 @@ export default function Login() {
|
||||
<Button
|
||||
title={!confirm ? "Receive code" : "Confirm code"}
|
||||
onPress={() =>
|
||||
!confirm ? signInWithPhoneNumber(phoneNumber) : confirmCode()
|
||||
!confirm
|
||||
? handleSignInWithPhoneNumber(phoneNumber).then(setConfirm)
|
||||
: 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>
|
||||
|
23
yarn.lock
23
yarn.lock
@ -2523,6 +2523,13 @@
|
||||
resolved "https://registry.yarnpkg.com/@pkgjs/parseargs/-/parseargs-0.11.0.tgz#a77ea742fab25775145434eb1d2328cf5013ac33"
|
||||
integrity sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg==
|
||||
|
||||
"@react-native-async-storage/async-storage@^1.21.0":
|
||||
version "1.21.0"
|
||||
resolved "https://registry.yarnpkg.com/@react-native-async-storage/async-storage/-/async-storage-1.21.0.tgz#d7e370028e228ab84637016ceeb495878b7a44c8"
|
||||
integrity sha512-JL0w36KuFHFCvnbOXRekqVAUplmOyT/OuCQkogo6X98MtpSaJOKEAeZnYO8JB0U/RIEixZaGI5px73YbRm/oag==
|
||||
dependencies:
|
||||
merge-options "^3.0.4"
|
||||
|
||||
"@react-native-camera-roll/camera-roll@^7.4.0":
|
||||
version "7.4.0"
|
||||
resolved "https://registry.yarnpkg.com/@react-native-camera-roll/camera-roll/-/camera-roll-7.4.0.tgz#931e25b076b40dc57ca6d380f0a85d494a120f06"
|
||||
@ -6958,6 +6965,11 @@ is-path-inside@^3.0.2, is-path-inside@^3.0.3:
|
||||
resolved "https://registry.yarnpkg.com/is-path-inside/-/is-path-inside-3.0.3.tgz#d231362e53a07ff2b0e0ea7fed049161ffd16283"
|
||||
integrity sha512-Fd4gABb+ycGAmKou8eMftCupSir5lRxqf4aD/vd0cD2qc4HL07OjCeuHMr8Ro4CoMaeCKDB0/ECBOVWjTwUvPQ==
|
||||
|
||||
is-plain-obj@^2.1.0:
|
||||
version "2.1.0"
|
||||
resolved "https://registry.yarnpkg.com/is-plain-obj/-/is-plain-obj-2.1.0.tgz#45e42e37fccf1f40da8e5f76ee21515840c09287"
|
||||
integrity sha512-YWnfyRwxL/+SsrWYfOpUtz5b3YD+nyfkHvjbcanzk8zgyO4ASD67uVMRt8k5bM4lLMDnXfriRhOpemw+NfT1eA==
|
||||
|
||||
is-plain-object@^2.0.4:
|
||||
version "2.0.4"
|
||||
resolved "https://registry.yarnpkg.com/is-plain-object/-/is-plain-object-2.0.4.tgz#2c163b3fafb1b606d9d17928f05c2a1c38e07677"
|
||||
@ -8183,6 +8195,13 @@ memory-cache@~0.2.0:
|
||||
resolved "https://registry.yarnpkg.com/memory-cache/-/memory-cache-0.2.0.tgz#7890b01d52c00c8ebc9d533e1f8eb17e3034871a"
|
||||
integrity sha512-OcjA+jzjOYzKmKS6IQVALHLVz+rNTMPoJvCztFaZxwG14wtAW7VRZjwTQu06vKCYOxh4jVnik7ya0SXTB0W+xA==
|
||||
|
||||
merge-options@^3.0.4:
|
||||
version "3.0.4"
|
||||
resolved "https://registry.yarnpkg.com/merge-options/-/merge-options-3.0.4.tgz#84709c2aa2a4b24c1981f66c179fe5565cc6dbb7"
|
||||
integrity sha512-2Sug1+knBjkaMsMgf1ctR1Ujx+Ayku4EdJN4Z+C2+JzoeF7A3OZ9KM2GY0CpQS51NR61LTurMJrRKPhSs3ZRTQ==
|
||||
dependencies:
|
||||
is-plain-obj "^2.1.0"
|
||||
|
||||
merge-stream@^2.0.0:
|
||||
version "2.0.0"
|
||||
resolved "https://registry.yarnpkg.com/merge-stream/-/merge-stream-2.0.0.tgz#52823629a14dd00c9770fb6ad47dc6310f2c1f60"
|
||||
@ -9658,9 +9677,9 @@ queue@6.0.2:
|
||||
dependencies:
|
||||
inherits "~2.0.3"
|
||||
|
||||
"railbird-gql@git+https://dev.railbird.ai/railbird/railbird-gql.git#db82f66c5d3600d90f09c813f71287e176dc078b":
|
||||
"railbird-gql@git+https://dev.railbird.ai/railbird/railbird-gql.git#838304efdd49a093bd8f9cea6cd6ef9e306d888a":
|
||||
version "1.0.0"
|
||||
resolved "git+https://dev.railbird.ai/railbird/railbird-gql.git#db82f66c5d3600d90f09c813f71287e176dc078b"
|
||||
resolved "git+https://dev.railbird.ai/railbird/railbird-gql.git#838304efdd49a093bd8f9cea6cd6ef9e306d888a"
|
||||
dependencies:
|
||||
"@apollo/client" "^3.9.2"
|
||||
"@graphql-codegen/cli" "^5.0.0"
|
||||
|
Loading…
Reference in New Issue
Block a user