Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

🔥[🐛] Firebase auth unable to fetch new token after one hour #6341

Closed
2 of 10 tasks
jadonhansen opened this issue Jun 26, 2022 · 2 comments
Closed
2 of 10 tasks

🔥[🐛] Firebase auth unable to fetch new token after one hour #6341

jadonhansen opened this issue Jun 26, 2022 · 2 comments
Labels
help: needs-triage Issue needs additional investigation/triaging. type: bug New bug report

Comments

@jadonhansen
Copy link

Issue

I am using firebase auth to sign-in to the application on iOS and Android, emulator and real device.
However, after exiting the app and re-entering once an hour has passed firebase auth is unable to fetch/refresh a new token and authenticate the current user again.
When making a request to firestore, on app startup, to try and fetch the user's data it does not throw an auth error it throws firestore/unavailable, which points to network connection. However, I have tried this on multiple devices and it is consistently not being able to refresh the auth token. I doubt it is network connection because if I just simply sign-in again it re-auths me correctly and fetches my data.

Below is some XCode debug with firebase debug on:

2022-06-25 00:44:52.630794+0200 weatherly[44340:820850] 8.15.0 - [Firebase/Auth][I-AUT000002] Token auto-refresh enabled.
2022-06-25 00:44:52.632236+0200 weatherly[44340:820850] 8.15.0 - [Firebase/Auth][I-AUT000004] Token auto-refresh scheduled in 00:00 for the new token.
2022-06-25 00:44:52.632925+0200 weatherly[44340:820850] 8.15.0 - [Firebase/Auth][I-AUT000017] Does not have valid access token. Estimated expiration date: 2022-06-24 22:08:53 +0000, current date: 2022-06-24 22:44:52 +0000
2022-06-25 00:44:52.634456+0200 weatherly[44340:820850] 8.15.0 - [Firebase/Auth][I-AUT000017] Fetching new token from backend.
2022-06-25 00:44:52.637212+0200 weatherly[44340:820850] 8.15.0 - [Firebase/Firestore][I-FST000001] Using full collection scan to execute query: Query(canonical_id=weatherly-users/b8g3PFda3NV5xBea5q7o0J5DdCk2|f:|ob:__name__asc)
2022-06-25 00:44:52.637697+0200 weatherly[44340:820850] 8.15.0 - [Firebase/Firestore][I-FST000001] Committing transaction: <LevelDbTransaction ExecuteQuery: 0 changes (0 bytes):>
2022-06-25 00:44:52.674947+0200 weatherly[44340:820841] 8.15.0 - [Firebase/Analytics][I-ACS023044] Successful upload. Got network response. Code, size: 204, -1
2022-06-25 00:44:52.689120+0200 weatherly[44340:820850] 8.15.0 - [Firebase/Analytics][I-ACS002002] Measurement timer scheduled to fire in approx. (s): -0.9368828535079956
2022-06-25 00:44:52.701770+0200 weatherly[44340:820850] 8.15.0 - [Firebase/Analytics][I-ACS002003] Measurement timer canceled
2022-06-25 00:44:53.231703+0200 weatherly[44340:820842] 8.15.0 - [Firebase/Auth][I-AUT000017] Fetching new token from backend.
2022-06-25 00:44:53.235433+0200 weatherly[44340:820842] 8.15.0 - [Firebase/Firestore][I-FST000001] WatchStream (7fbe0d2480a8) Stream error: 'Unknown: An internal error has occurred, print and inspect the error details for more information.'
2022-06-25 00:44:53.242762+0200 weatherly[44340:820842] 8.15.0 - [Firebase/Firestore][I-FST000001] Could not reach Cloud Firestore backend. Connection failed 1 times. Most recent error: An internal error has occurred, print and inspect the error details for more information.
2022-06-25 00:44:53.252760+0200 weatherly[44340:820842] 8.15.0 - [Firebase/Firestore][I-FST000001] WatchStream (7fbe0d2480a8) backoff
2022-06-25 00:44:53.255128+0200 weatherly[44340:820842] 8.15.0 - [Firebase/Firestore][I-FST000001] WatchStream (7fbe0d2480a8) start
2022-06-25 00:44:53.869949+0200 weatherly[44340:820850] 8.15.0 - [Firebase/Auth][I-AUT000003] Token auto-refresh re-scheduled in 01:00 because of error on previous refresh attempt.
2022-06-25 00:44:53.870480+0200 weatherly[44340:820850] 8.15.0 - [Firebase/Auth][I-AUT000017] Does not have valid access token. Estimated expiration date: 2022-06-24 22:08:53 +0000, current date: 2022-06-24 22:44:53 +0000
2022-06-25 00:44:53.874458+0200 weatherly[44340:820850] 8.15.0 - [Firebase/Auth][I-AUT000017] Fetching new token from backend.
2022-06-25 00:44:54.004084+0200 weatherly[44340:820840] 8.15.0 - [Firebase/Firestore][I-FST000001] Committing transaction: <LevelDbTransaction Release target: 2 changes (175 bytes):
2022-06-25 00:44:54.792041+0200 weatherly[44340:820842] 8.15.0 - [Firebase/Firestore][I-FST000001] WatchStream (7fbe0d2480a8) Stream error: 'Unknown: An internal error has occurred, print and inspect the error details for more information.'

I have tried getting forcing a refresh of the token after an error is found but that does not seem to work either.
Code to refresh: firebase.auth().currentUser.getIdToken(true);


Project Files

Javascript

Click To Expand

package.json:

{
  "scripts": {
    "start": "react-native start",
    "android": "react-native run-android",
    "ios": "react-native run-ios",
    "web": "expo start --web",
    "eject": "expo eject",
    "lint": "eslint --ext .jsx --ext .js app/"
  },
  "dependencies": {
    "@react-native-async-storage/async-storage": "~1.15.0",
    "@react-native-community/masked-view": "^0.1.11",
    "@react-native-firebase/analytics": "^14.9.4",
    "@react-native-firebase/app": "^14.9.4",
    "@react-native-firebase/auth": "^14.9.4",
    "@react-native-firebase/crashlytics": "^14.9.4",
    "@react-native-firebase/firestore": "^14.9.4",
    "@react-native-firebase/functions": "^14.9.4",
    "@react-navigation/bottom-tabs": "^5.11.15",
    "@react-navigation/native": "^5.9.8",
    "@react-navigation/stack": "^5.14.9",
    "expo": "^44.0.0",
    "expo-haptics": "~11.1.0",
    "expo-in-app-purchases": "~12.1.0",
    "expo-linking": "~3.0.0",
    "expo-location": "~14.0.1",
    "expo-network": "~4.1.0",
    "expo-splash-screen": "~0.14.1",
    "expo-status-bar": "~1.2.0",
    "expo-updates": "~0.11.6",
    "react": "17.0.1",
    "react-dom": "17.0.1",
    "react-native": "0.64.3",
    "react-native-chart-kit": "^6.11.0",
    "react-native-dotenv": "^3.2.0",
    "react-native-elements": "^3.4.2",
    "react-native-fast-image": "^8.5.11",
    "react-native-gesture-handler": "~2.1.0",
    "react-native-maps": "0.29.4",
    "react-native-notifier": "^1.7.1",
    "react-native-reanimated": "^2.3.1",
    "react-native-restart": "0.0.22",
    "react-native-safe-area-context": "3.3.2",
    "react-native-screens": "~3.10.1",
    "react-native-snap-carousel": "^3.9.1",
    "react-native-svg": "12.1.1",
    "react-native-vector-icons": "^9.1.0",
    "react-native-web": "0.17.1"
  },
  "devDependencies": {
    "@babel/core": "^7.12.9",
    "eslint": "^8.18.0",
    "eslint-plugin-react": "^7.30.1",
    "metro-react-native-babel-preset": "^0.66.2"
  },
  "private": true,
  "name": "weatherly",
  "version": "1.0.0"
}

firebase.json for react-native-firebase v6:

{
	"react-native": {
		"crashlytics_debug_enabled": false,
		"crashlytics_javascript_exception_handler_chaining_enabled": false,
		"android_bypass_emulator_url_remap": true
	}
}

iOS

Click To Expand

ios/Podfile:

  • I'm not using Pods
  • I'm using Pods and my Podfile looks like:
require File.join(File.dirname(`node --print "require.resolve('expo/package.json')"`), "scripts/autolinking")
require File.join(File.dirname(`node --print "require.resolve('react-native/package.json')"`), "scripts/react_native_pods")
require File.join(File.dirname(`node --print "require.resolve('@react-native-community/cli-platform-ios/package.json')"`), "native_modules")

$RNFirebaseAsStaticFramework = true

platform :ios, '12.0'

require 'json'
podfile_properties = JSON.parse(File.read('./Podfile.properties.json')) rescue {}

target 'Weatherly' do
  use_frameworks!
  use_expo_modules!
  config = use_native_modules!

  use_react_native!(
    :path => config[:reactNativePath],
    :hermes_enabled => podfile_properties['expo.jsEngine'] == 'hermes'
  )

  # Uncomment to opt-in to using Flipper
  #
  # if !ENV['CI']
  #   use_flipper!('Flipper' => '0.75.1', 'Flipper-Folly' => '2.5.3', 'Flipper-RSocket' => '1.3.1')
  #   post_install do |installer|
  #     flipper_post_install(installer)
  #   end
  # end

  pod 'RNVectorIcons', :path => '../node_modules/react-native-vector-icons'

  post_install do |installer|
    react_native_post_install(installer)
  
    # Workaround `Cycle inside FBReactNativeSpec` error for react-native 0.64
    # Reference: https://github.com/software-mansion/react-native-screens/issues/842#issuecomment-812543933
    installer.pods_project.targets.each do |target|
      if (target.name&.eql?('FBReactNativeSpec'))
        target.build_phases.each do |build_phase|
          if (build_phase.respond_to?(:name) && build_phase.name.eql?('[CP-User] Generate Specs'))
            target.build_phases.move(build_phase, 0)
          end
        end
      end
    end
  end

end

AppDelegate.m:

#import "AppDelegate.h"

// firebase config
#import <Firebase.h>

#import <React/RCTBridge.h>
#import <React/RCTBundleURLProvider.h>
#import <React/RCTRootView.h>
#import <React/RCTLinkingManager.h>

#if defined(FB_SONARKIT_ENABLED) && __has_include(<FlipperKit/FlipperClient.h>)
#import <FlipperKit/FlipperClient.h>
#import <FlipperKitLayoutPlugin/FlipperKitLayoutPlugin.h>
#import <FlipperKitUserDefaultsPlugin/FKUserDefaultsPlugin.h>
#import <FlipperKitNetworkPlugin/FlipperKitNetworkPlugin.h>
#import <SKIOSNetworkPlugin/SKIOSNetworkAdapter.h>
#import <FlipperKitReactPlugin/FlipperKitReactPlugin.h>

static void InitializeFlipper(UIApplication *application) {
  FlipperClient *client = [FlipperClient sharedClient];
  SKDescriptorMapper *layoutDescriptorMapper = [[SKDescriptorMapper alloc] initWithDefaults];
  [client addPlugin:[[FlipperKitLayoutPlugin alloc] initWithRootNode:application withDescriptorMapper:layoutDescriptorMapper]];
  [client addPlugin:[[FKUserDefaultsPlugin alloc] initWithSuiteName:nil]];
  [client addPlugin:[FlipperKitReactPlugin new]];
  [client addPlugin:[[FlipperKitNetworkPlugin alloc] initWithNetworkAdapter:[SKIOSNetworkAdapter new]]];
  [client start];
}
#endif

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  // firebase config
  [FIRApp configure];

#if defined(FB_SONARKIT_ENABLED) && __has_include(<FlipperKit/FlipperClient.h>)
  InitializeFlipper(application);
#endif

  RCTBridge *bridge = [self.reactDelegate createBridgeWithDelegate:self launchOptions:launchOptions];
  RCTRootView *rootView = [self.reactDelegate createRootViewWithBridge:bridge moduleName:@"main" initialProperties:nil];
  rootView.backgroundColor = [UIColor whiteColor];

  self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
  UIViewController *rootViewController = [self.reactDelegate createRootViewController];
  rootViewController.view = rootView;
  self.window.rootViewController = rootViewController;
  [self.window makeKeyAndVisible];

  [super application:application didFinishLaunchingWithOptions:launchOptions];

  return YES;
}

- (NSArray<id<RCTBridgeModule>> *)extraModulesForBridge:(RCTBridge *)bridge
{
  // If you'd like to export some custom RCTBridgeModules that are not Expo modules, add them here!
  return @[];
}

- (NSURL *)sourceURLForBridge:(RCTBridge *)bridge {
 #ifdef DEBUG
  return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil];
 #else
  return [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];
 #endif
}

// Linking API
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options {
  return [RCTLinkingManager application:application openURL:url options:options];
}

// Universal Links
- (BOOL)application:(UIApplication *)application continueUserActivity:(nonnull NSUserActivity *)userActivity restorationHandler:(nonnull void (^)(NSArray<id<UIUserActivityRestoring>> * _Nullable))restorationHandler {
  return [RCTLinkingManager application:application
                   continueUserActivity:userActivity
                     restorationHandler:restorationHandler];
}

@end


Android

Click To Expand

Have you converted to AndroidX?

  • my application is an AndroidX application?
  • I am using android/gradle.settings jetifier=true for Android compatibility?
  • I am using the NPM package jetifier for react-native compatibility?

android/build.gradle:

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    ext {
        buildToolsVersion = "29.0.3"
        minSdkVersion = 21
        compileSdkVersion = 30
        targetSdkVersion = 30
    }
    repositories {
        google()
        mavenCentral()
        jcenter()
    }
    dependencies {
        classpath("com.android.tools.build:gradle:4.1.0")

        // added for firebase config
        classpath 'com.google.gms:google-services:4.3.10'
        classpath 'com.google.firebase:firebase-crashlytics-gradle:2.8.1'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        mavenLocal()
        maven {
            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
            url(new File(["node", "--print", "require.resolve('react-native/package.json')"].execute(null, rootDir).text.trim(), "../android"))
        }
        maven {
            // Android JSC is installed from npm
            url(new File(["node", "--print", "require.resolve('jsc-android/package.json')"].execute(null, rootDir).text.trim(), "../dist"))
        }

        google()
        mavenCentral()
        jcenter()
        maven { url 'https://www.jitpack.io' }
    }
}

android/app/build.gradle:

apply plugin: "com.android.application"
apply plugin: 'com.google.gms.google-services'
apply plugin: 'com.google.firebase.crashlytics'

import com.android.build.OutputFile

/**
 * The react.gradle file registers a task for each build variant (e.g. bundleDebugJsAndAssets
 * and bundleReleaseJsAndAssets).
 * These basically call `react-native bundle` with the correct arguments during the Android build
 * cycle. By default, bundleDebugJsAndAssets is skipped, as in debug/dev mode we prefer to load the
 * bundle directly from the development server. Below you can see all the possible configurations
 * and their defaults. If you decide to add a configuration block, make sure to add it before the
 * `apply from: "../../node_modules/react-native/react.gradle"` line.
 *
 * project.ext.react = [
 *   // the name of the generated asset file containing your JS bundle
 *   bundleAssetName: "index.android.bundle",
 *
 *   // the entry file for bundle generation. If none specified and
 *   // "index.android.js" exists, it will be used. Otherwise "index.js" is
 *   // default. Can be overridden with ENTRY_FILE environment variable.
 *   entryFile: "index.android.js",
 *
 *   // https://reactnative.dev/docs/performance#enable-the-ram-format
 *   bundleCommand: "ram-bundle",
 *
 *   // whether to bundle JS and assets in debug mode
 *   bundleInDebug: false,
 *
 *   // whether to bundle JS and assets in release mode
 *   bundleInRelease: true,
 *
 *   // whether to bundle JS and assets in another build variant (if configured).
 *   // See http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Build-Variants
 *   // The configuration property can be in the following formats
 *   //         'bundleIn${productFlavor}${buildType}'
 *   //         'bundleIn${buildType}'
 *   // bundleInFreeDebug: true,
 *   // bundleInPaidRelease: true,
 *   // bundleInBeta: true,
 *
 *   // whether to disable dev mode in custom build variants (by default only disabled in release)
 *   // for example: to disable dev mode in the staging build type (if configured)
 *   devDisabledInStaging: true,
 *   // The configuration property can be in the following formats
 *   //         'devDisabledIn${productFlavor}${buildType}'
 *   //         'devDisabledIn${buildType}'
 *
 *   // the root of your project, i.e. where "package.json" lives
 *   root: "../../",
 *
 *   // where to put the JS bundle asset in debug mode
 *   jsBundleDirDebug: "$buildDir/intermediates/assets/debug",
 *
 *   // where to put the JS bundle asset in release mode
 *   jsBundleDirRelease: "$buildDir/intermediates/assets/release",
 *
 *   // where to put drawable resources / React Native assets, e.g. the ones you use via
 *   // require('./image.png')), in debug mode
 *   resourcesDirDebug: "$buildDir/intermediates/res/merged/debug",
 *
 *   // where to put drawable resources / React Native assets, e.g. the ones you use via
 *   // require('./image.png')), in release mode
 *   resourcesDirRelease: "$buildDir/intermediates/res/merged/release",
 *
 *   // by default the gradle tasks are skipped if none of the JS files or assets change; this means
 *   // that we don't look at files in android/ or ios/ to determine whether the tasks are up to
 *   // date; if you have any other folders that you want to ignore for performance reasons (gradle
 *   // indexes the entire tree), add them here. Alternatively, if you have JS files in android/
 *   // for example, you might want to remove it from here.
 *   inputExcludes: ["android/**", "ios/**"],
 *
 *   // override which node gets called and with what additional arguments
 *   nodeExecutableAndArgs: ["node"],
 *
 *   // supply additional arguments to the packager
 *   extraPackagerArgs: []
 * ]
 */

project.ext.react = [
    enableHermes: false,
    cliPath: new File(["node", "--print", "require.resolve('react-native/package.json')"].execute(null, rootDir).text.trim()).getParentFile().getAbsolutePath() + "/cli.js",
    hermesCommand: new File(["node", "--print", "require.resolve('hermes-engine/package.json')"].execute(null, rootDir).text.trim()).getParentFile().getAbsolutePath() + "/%OS-BIN%/hermesc",
    composeSourceMapsPath: new File(["node", "--print", "require.resolve('react-native/package.json')"].execute(null, rootDir).text.trim()).getParentFile().getAbsolutePath() + "/scripts/compose-source-maps.js",
]

apply from: new File(["node", "--print", "require.resolve('react-native/package.json')"].execute(null, rootDir).text.trim(), "../react.gradle")

// for react-native-vector-icons
project.ext.vectoricons = [
    iconFontNames: [ 'Feather.ttf', 'FontAwesome.ttf', 'FontAwesome5_Brands.ttf', 'FontAwesome5_Regular.ttf', 'FontAwesome5_Solid.ttf', 'Ionicons.ttf' ]
]
apply from: "../../node_modules/react-native-vector-icons/fonts.gradle"

/**
 * Set this to true to create two separate APKs instead of one:
 *   - An APK that only works on ARM devices
 *   - An APK that only works on x86 devices
 * The advantage is the size of the APK is reduced by about 4MB.
 * Upload all the APKs to the Play Store and people will download
 * the correct one based on the CPU architecture of their device.
 */
def enableSeparateBuildPerCPUArchitecture = false

/**
 * Run Proguard to shrink the Java bytecode in release builds.
 */
def enableProguardInReleaseBuilds = false

/**
 * The preferred build flavor of JavaScriptCore.
 *
 * For example, to use the international variant, you can use:
 * `def jscFlavor = 'org.webkit:android-jsc-intl:+'`
 *
 * The international variant includes ICU i18n library and necessary data
 * allowing to use e.g. `Date.toLocaleString` and `String.localeCompare` that
 * give correct results when using with locales other than en-US.  Note that
 * this variant is about 6MiB larger per architecture than default.
 */
def jscFlavor = 'org.webkit:android-jsc:+'

/**
 * Whether to enable the Hermes VM.
 *
 * This should be set on project.ext.react and mirrored here.  If it is not set
 * on project.ext.react, JavaScript will not be compiled to Hermes Bytecode
 * and the benefits of using Hermes will therefore be sharply reduced.
 */
def enableHermes = project.ext.react.get("enableHermes", false);

android {
    compileSdkVersion rootProject.ext.compileSdkVersion

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    defaultConfig {
        applicationId 'com.jadonhansen.weatherly'
        minSdkVersion rootProject.ext.minSdkVersion
        targetSdkVersion rootProject.ext.targetSdkVersion
        versionCode 61
        versionName "1.8.3"
    }
    splits {
        abi {
            reset()
            enable enableSeparateBuildPerCPUArchitecture
            universalApk false  // If true, also generate a universal APK
            include "armeabi-v7a", "x86", "arm64-v8a", "x86_64"
        }
    }
    signingConfigs {
        debug {
            storeFile file('debug.keystore')
            storePassword 'android'
            keyAlias 'androiddebugkey'
            keyPassword 'android'
        }
        release {
            if (project.hasProperty('MYAPP_UPLOAD_STORE_FILE')) {
                storeFile file(MYAPP_UPLOAD_STORE_FILE)
                storePassword MYAPP_UPLOAD_STORE_PASSWORD
                keyAlias MYAPP_UPLOAD_KEY_ALIAS
                keyPassword MYAPP_UPLOAD_KEY_PASSWORD
            }
        }
    }
    buildTypes {
        debug {
            signingConfig signingConfigs.release
        }
        release {
            /* Add the firebaseCrashlytics extension (by default,
            * it's disabled to improve build speeds) and set
            * nativeSymbolUploadEnabled to true along with a pointer to native libs. */

            firebaseCrashlytics {
                nativeSymbolUploadEnabled true
                unstrippedNativeLibsDir 'build/intermediates/merged_native_libs/release/out/lib'
            }

            // Caution! In production, you need to generate your own keystore file.
            // see https://reactnative.dev/docs/signed-apk-android.
            signingConfig signingConfigs.release
            minifyEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
        }
    }

    // applicationVariants are e.g. debug, release
    applicationVariants.all { variant ->
        variant.outputs.each { output ->
            // For each separate APK per architecture, set a unique version code as described here:
            // https://developer.android.com/studio/build/configure-apk-splits.html
            def versionCodes = ["armeabi-v7a": 1, "x86": 2, "arm64-v8a": 3, "x86_64": 4]
            def abi = output.getFilter(OutputFile.ABI)
            if (abi != null) {  // null for the universal-debug, universal-release variants
                output.versionCodeOverride =
                        versionCodes.get(abi) * 1048576 + defaultConfig.versionCode
            }

        }
    }
}

dependencies {
    implementation fileTree(dir: "libs", include: ["*.jar"])
    //noinspection GradleDynamicVersion
    implementation "com.facebook.react:react-native:+"  // From node_modules

    def isGifEnabled = (findProperty('expo.gif.enabled') ?: "") == "true";
    def isWebpEnabled = (findProperty('expo.webp.enabled') ?: "") == "true";
    def isWebpAnimatedEnabled = (findProperty('expo.webp.animated') ?: "") == "true";

    // If your app supports Android versions before Ice Cream Sandwich (API level 14)
    // All fresco packages should use the same version
    if (isGifEnabled || isWebpEnabled) {
        implementation 'com.facebook.fresco:fresco:2.0.0'
        implementation 'com.facebook.fresco:imagepipeline-okhttp3:2.0.0'
    }

    if (isGifEnabled) {
        // For animated gif support
        implementation 'com.facebook.fresco:animated-gif:2.0.0'
    }

    if (isWebpEnabled) {
        // For webp support
        implementation 'com.facebook.fresco:webpsupport:2.0.0'
        if (isWebpAnimatedEnabled) {
            // Animated webp support
            implementation 'com.facebook.fresco:animated-webp:2.0.0'
        }
    }

    implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.0.0"

    debugImplementation("com.facebook.flipper:flipper:${FLIPPER_VERSION}") {
      exclude group:'com.facebook.fbjni'
    }
    debugImplementation("com.facebook.flipper:flipper-network-plugin:${FLIPPER_VERSION}") {
        exclude group:'com.facebook.flipper'
        exclude group:'com.squareup.okhttp3', module:'okhttp'
    }
    debugImplementation("com.facebook.flipper:flipper-fresco-plugin:${FLIPPER_VERSION}") {
        exclude group:'com.facebook.flipper'
    }

    if (enableHermes) {
        debugImplementation files(new File(["node", "--print", "require.resolve('hermes-engine/package.json')"].execute(null, rootDir).text.trim(), "../android/hermes-debug.aar"))
        releaseImplementation files(new File(["node", "--print", "require.resolve('hermes-engine/package.json')"].execute(null, rootDir).text.trim(), "../android/hermes-release.aar"))
    } else {
        implementation jscFlavor
    }
}

// Run this once to be able to run the application with BUCK
// puts all compile dependencies into folder libs for BUCK to use
task copyDownloadableDepsToLibs(type: Copy) {
    from configurations.compile
    into 'libs'
}

apply from: new File(["node", "--print", "require.resolve('@react-native-community/cli-platform-android/package.json')"].execute(null, rootDir).text.trim(), "../native_modules.gradle");
applyNativeModulesAppBuildGradle(project)

android/settings.gradle:

rootProject.name = 'Weatherly'

apply from: new File(["node", "--print", "require.resolve('expo/package.json')"].execute(null, rootDir).text.trim(), "../scripts/autolinking.gradle");
useExpoModules()

apply from: new File(["node", "--print", "require.resolve('@react-native-community/cli-platform-android/package.json')"].execute(null, rootDir).text.trim(), "../native_modules.gradle");
applyNativeModulesSettingsGradle(settings)

include ':app'

MainApplication.java:

package com.jadonhansen.weatherly;

import android.app.Application;
import android.content.Context;
import android.content.res.Configuration;
import androidx.annotation.NonNull;

import com.facebook.react.PackageList;
import com.facebook.react.ReactApplication;
import com.oblador.vectoricons.VectorIconsPackage;
import com.facebook.react.ReactInstanceManager;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.react.shell.MainReactPackage;
import com.facebook.soloader.SoLoader;

import expo.modules.ApplicationLifecycleDispatcher;
import expo.modules.ReactNativeHostWrapper;

import com.facebook.react.bridge.JSIModulePackage;
import com.swmansion.reanimated.ReanimatedJSIModulePackage;

import java.lang.reflect.InvocationTargetException;
import java.util.List;

public class MainApplication extends Application implements ReactApplication {

  private final ReactNativeHost mReactNativeHost = new ReactNativeHostWrapper(
    this,
    new ReactNativeHost(this) {
      @Override
      public boolean getUseDeveloperSupport() {
        return BuildConfig.DEBUG;
      }

    @Override
    protected List<ReactPackage> getPackages() {
      @SuppressWarnings("UnnecessaryLocalVariable")
      List<ReactPackage> packages = new PackageList(this).getPackages();
      // Packages that cannot be autolinked yet can be added manually here, for example:
      // packages.add(new MyReactNativePackage());
      return packages;
    }

    @Override
    protected String getJSMainModuleName() {
      return "index";
    }

    @Override
    protected JSIModulePackage getJSIModulePackage() {
      return new ReanimatedJSIModulePackage();
    }
  });

  @Override
  public ReactNativeHost getReactNativeHost() {
    return mReactNativeHost;
  }

  @Override
  public void onCreate() {
    super.onCreate();
    SoLoader.init(this, /* native exopackage */ false);

    initializeFlipper(this, getReactNativeHost().getReactInstanceManager());
    ApplicationLifecycleDispatcher.onApplicationCreate(this);
  }

  @Override
  public void onConfigurationChanged(@NonNull Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    ApplicationLifecycleDispatcher.onConfigurationChanged(this, newConfig);
  }

  /**
   * Loads Flipper in React Native templates. Call this in the onCreate method
   * with something like initializeFlipper(this,
   * getReactNativeHost().getReactInstanceManager());
   *
   * @param context
   * @param reactInstanceManager
   */
  private static void initializeFlipper(Context context, ReactInstanceManager reactInstanceManager) {
    if (BuildConfig.DEBUG) {
      try {
        /*
         * We use reflection here to pick up the class that initializes Flipper, since
         * Flipper library is not available in release mode
         */
        Class<?> aClass = Class.forName("com.jadonhansen.weatherly.ReactNativeFlipper");
        aClass.getMethod("initializeFlipper", Context.class, ReactInstanceManager.class).invoke(null, context,
            reactInstanceManager);
      } catch (ClassNotFoundException e) {
        e.printStackTrace();
      } catch (NoSuchMethodException e) {
        e.printStackTrace();
      } catch (IllegalAccessException e) {
        e.printStackTrace();
      } catch (InvocationTargetException e) {
        e.printStackTrace();
      }
    }
  }
}

AndroidManifest.xml:

<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.jadonhansen.weatherly" xmlns:tools="http://schemas.android.com/tools">
  <uses-permission android:name="android.permission.INTERNET"/>
  <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
  <uses-permission tools:node="remove" android:name="android.permission.READ_PHONE_STATE"/>
  <uses-permission android:name="android.permission.VIBRATE"/>
  <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS"/>
  <uses-permission tools:node="remove" android:name="android.permission.READ_EXTERNAL_STORAGE"/>
  <uses-permission tools:node="remove" android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
  <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
  <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
  <uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
  <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
  <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
  <uses-permission android:name="android.permission.WAKE_LOCK"/>
  <uses-permission android:name="com.android.vending.BILLING"/>
  <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE"/>
  <application android:name=".MainApplication" android:label="@string/app_name" android:icon="@mipmap/ic_launcher" android:roundIcon="@mipmap/ic_launcher" android:allowBackup="true" android:theme="@style/AppTheme">
    <meta-data android:name="expo.modules.updates.EXPO_UPDATE_URL" android:value="https://exp.host/@jadonhansen/Weatherly" />
    <meta-data android:name="expo.modules.updates.EXPO_SDK_VERSION" android:value="44.0.0" />
    <meta-data android:name="expo.modules.updates.ENABLED" android:value="true"/>
    <meta-data android:name="expo.modules.updates.EXPO_UPDATES_CHECK_ON_LAUNCH" android:value="ON_LOAD"/>
    <meta-data android:name="expo.modules.updates.EXPO_UPDATES_LAUNCH_WAIT_MS" android:value="0"/>
    <meta-data android:name="com.google.android.geo.API_KEY" android:value=":0"/>
    <meta-data android:name="expo.modules.updates.EXPO_RELEASE_CHANNEL" android:value="default" />

  <activity
    android:name=".MainActivity" android:label="@string/app_name" android:configChanges="keyboard|keyboardHidden|orientation|screenSize|uiMode" android:launchMode="singleTask" android:windowSoftInputMode="adjustResize" android:theme="@style/Theme.App.SplashScreen" android:screenOrientation="portrait">
      <intent-filter>
        <action android:name="android.intent.action.MAIN"/>
        <category android:name="android.intent.category.LAUNCHER"/>
      </intent-filter>
      <intent-filter>
        <action android:name="android.intent.action.VIEW"/>
        <category android:name="android.intent.category.DEFAULT"/>
        <category android:name="android.intent.category.BROWSABLE"/>
        <data android:scheme="com.jadonhansen.weatherly"/>
      </intent-filter>
    </activity>
    <activity android:name="com.facebook.react.devsupport.DevSettingsActivity"/>
    <uses-library android:name="org.apache.http.legacy" android:required="false"/>
  </application>
</manifest>


Environment

Click To Expand

react-native info output:

System:
    OS: macOS 12.3.1
    CPU: (4) x64 Intel(R) Core(TM) i5-7360U CPU @ 2.30GHz
    Memory: 89.39 MB / 8.00 GB
    Shell: 5.8 - /bin/zsh
  Binaries:
    Node: 16.15.1 - /usr/local/bin/node
    Yarn: Not Found
    npm: 8.11.0 - /usr/local/bin/npm
    Watchman: 4.9.0 - /usr/local/bin/watchman
  Managers:
    CocoaPods: 1.11.2 - /usr/local/bin/pod
  SDKs:
    iOS SDK:
      Platforms: DriverKit 21.4, iOS 15.5, macOS 12.3, tvOS 15.4, watchOS 8.5
    Android SDK:
      API Levels: 29, 30, 31
      Build Tools: 29.0.2, 30.0.3
      System Images: android-24 | Google Play Intel x86 Atom, android-26 | Google Play Intel x86 Atom, android-27 | Google Play Intel x86 Atom, android-28 | Google Play Intel x86 Atom, android-29 | Google Play Intel x86 Atom, android-30 | Google APIs Intel x86 Atom
      Android NDK: Not Found
  IDEs:
    Android Studio: 2021.1 AI-211.7628.21.2111.8092744
    Xcode: 13.4.1/13F100 - /usr/bin/xcodebuild
  Languages:
    Java: 13.0.2 - /usr/bin/javac
  npmPackages:
    @react-native-community/cli: Not Found
    react: 17.0.1 => 17.0.1 
    react-native: 0.64.3 => 0.64.3 
    react-native-macos: Not Found
  npmGlobalPackages:
    *react-native*: Not Found
  • Platform that you're experiencing the issue on:
    • iOS
    • Android
    • iOS but have not tested behavior on Android
    • Android but have not tested behavior on iOS
    • Both
  • react-native-firebase version you're using that has this issue:
    • 14.9.4
  • Firebase module(s) you're using that has the issue:
    • @react-native-firebase/auth
  • Are you using TypeScript?
    • N


@jadonhansen jadonhansen added help: needs-triage Issue needs additional investigation/triaging. type: bug New bug report labels Jun 26, 2022
@jadonhansen
Copy link
Author

jadonhansen commented Jun 27, 2022

Important to note that I am using the current authed-in user's ID to fetch their firestore doc.
I am fetching with source: "server" and it fails with firestore/unavailable. Fetching with source: "default" works but for my use case I need to be able to fetch the users doc on app load and I doubt it is a network problem as I am spotting token refresh issues in the console and have tested on multiple devices with fast internet.

If I sign-in again after the app has loaded, and failed to authenticate the first time, it then authenticates properly and fetches user's doc with no problem even with source: "server".

@mikehardy
Copy link
Collaborator

This reminds me of a problem people had where the underlying error was one of a few things

The underlying thing was a failure of the refresh token to exchange correctly for an access token, so after the access token expired the user was locked out

This is not a module error though - it's going to be a duplicate of 4466 or 5522 depending on the underlying cause, so it's not actionable here which means this is close-able

I understand this particular issue is subtle unfortunately, hopefully the pointers above in combination with watching adb logcat and/or Xcode console help

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
help: needs-triage Issue needs additional investigation/triaging. type: bug New bug report
Projects
None yet
Development

No branches or pull requests

2 participants