invertase / react-native-firebase

🔥 A well-tested feature-rich modular Firebase implementation for React Native. Supports both iOS & Android platforms for all Firebase services.
https://rnfirebase.io
Other
11.71k stars 2.22k forks source link

🔥[🐛] emailVerified stays false even after clicking on link #5465

Closed KrisLau closed 3 years ago

KrisLau commented 3 years ago

Issue

So after the user signs up using this signup method:

async function signup(email, password) {
    await auth().createUserWithEmailAndPassword(email, password);
    await auth().currentUser.sendEmailVerification();
  }

Then display a screen to ask users to click on the email verification link in their email and provide a button to go to the login page. On the login screen, I have the login button setup to check auth?.currentUser?.emailVerified. For some reason, after I click on the link then login, it always returns false.

Login button logic:

<ButtonGradient
            onPress={() => {
              isEmailValid(email) &&
                isPasswordValid(pass) &&
                auth
                  .login(email, pass)
                  .then(
                    !auth.isEmailVerified &&
                      Toast.show('Email has not been verified!'),
                  )
                  .catch(error => {
                    switch (error.code) {
                      case 'auth/user-not-found':
                        Toast.show(
                          setEmailError(
                            'Account with this email does not exist',
                          ),
                          Toast.LONG,
                        );
                        break;
                      case 'auth/invalid-email':
                        setEmailError('Account with this email does not exist');
                        break;
                      case 'auth/wrong-password':
                        setPassError('Incorrect password');
                        break;
                      case 'auth/too-many-requests':
                        Toast.show(
                          'You have entered the incorrect password too many times! Try again later or tap on "Forgot Password" ',
                          Toast.LONG,
                        );
                        break;
                      default:
                        Toast.show(error.message, Toast.LONG);
                        break;
                    }
                  });
            }}
            text={'Login'}
          />

Things I've tried:


Project Files

Javascript

Click To Expand

#### `package.json`: ```json { "name": "Prototype", "version": "0.0.1", "private": true, "scripts": { "android": "react-native run-android", "ios": "react-native run-ios", "start": "react-native start", "test": "jest --verbose", "lint": "eslint .", "prestorybook": "rnstl" }, "config": { "react-native-storybook-loader": { "searchDir": [ "./storybook/stories" ], "pattern": "**/*.stories.js", "outputFile": "./storybook/storyLoader.js" } }, "dependencies": { "@react-native-clipboard/clipboard": "^1.7.0", "@react-native-community/geolocation": "^2.0.2", "@react-native-community/masked-view": "^0.1.10", "@react-native-firebase/app": "^12.1.0", "@react-native-firebase/auth": "^12.1.0", "@react-native-google-signin/google-signin": "^6.0.1", "@react-native-picker/picker": "^1.15.0", "@react-navigation/bottom-tabs": "^5.11.11", "@react-navigation/native": "^5.9.4", "@react-navigation/stack": "^5.14.4", "@storybook/react": "^3.4.12", "date-fns": "^2.21.3", "expo-av": "^9.1.2", "expo-video-thumbnails": "^5.1.0", "lodash": "^4.17.21", "react": "^17.0.2", "react-native": "^0.64.0", "react-native-apple-authentication": "^2.0.0", "react-native-autolink": "^4.0.0", "react-native-calendars": "^1.1260.0", "react-native-confirmation-code-field": "^7.1.0", "react-native-date-picker": "^3.3.0", "react-native-draggable-flatlist": "^2.6.2", "react-native-elements": "^3.4.1", "react-native-fbsdk-next": "^4.3.0", "react-native-gesture-handler": "^1.10.3", "react-native-google-places-autocomplete": "^2.2.0", "react-native-image-picker": "^4.0.3", "react-native-keyboard-aware-scroll-view": "^0.9.4", "react-native-linear-gradient": "^2.5.6", "react-native-maps": "0.28.0", "react-native-pager-view": "^5.2.1", "react-native-pulse": "^1.0.7", "react-native-reanimated": "^2.1.0", "react-native-safe-area-context": "^3.2.0", "react-native-screens": "^3.1.1", "react-native-simple-toast": "^1.1.3", "react-native-tab-view": "^3.0.1", "react-native-unimodules": "^0.13.3", "react-native-vector-icons": "^8.1.0", "react-native-webview": "^11.6.4" }, "devDependencies": { "@babel/core": "^7.14.6", "@babel/runtime": "^7.14.6", "@react-native-async-storage/async-storage": "^1.15.5", "@react-native-community/eslint-config": "^3.0.0", "@storybook/addon-actions": "^6.2.9", "@storybook/addon-knobs": "^6.2.9", "@storybook/addon-links": "^5.3.21", "@storybook/addon-ondevice-actions": "^5.3.23", "@storybook/addon-ondevice-knobs": "^5.3.25", "@storybook/react-native": "^5.3.25", "@storybook/react-native-server": "^5.3.23", "@types/jest": "^26.0.22", "@types/react": "^17.0.3", "@types/react-native": "^0.64.2", "@types/react-test-renderer": "^17.0.1", "babel-jest": "^27.0.2", "babel-loader": "^8.2.2", "babel-plugin-transform-remove-console": "^6.9.4", "eslint": "^7.29.0", "eslint-plugin-react": "^7.24.0", "eslint-plugin-react-native": "^3.11.0", "jest": "^27.0.4", "metro-react-native-babel-preset": "^0.66.0", "react-dom": "^17.0.2", "react-native-dev-menu": "^4.0.2", "react-native-storybook-loader": "^2.0.4", "react-refresh": "^0.10.0", "react-test-renderer": "17.0.1", "typescript": "^4.2.4" }, "jest": { "preset": "react-native", "setupFiles": [ "./node_modules/react-native-gesture-handler/jestSetup.js" ], "moduleFileExtensions": ["ts", "tsx", "js", "jsx", "json", "node"], "transformIgnorePatterns": ["node_modules/(?!react-native|react-navigation)/"] } } ``` #### `firebase.json` for react-native-firebase v6: ```json # N/A ```

iOS

Click To Expand

#### `ios/Podfile`: - [x] I'm not using Pods - [] I'm using Pods and my Podfile looks like: ```ruby # N/A ``` #### `AppDelegate.m`: ```objc // N/A ```


Android

Click To Expand

#### Have you converted to AndroidX? - [x] my application is an AndroidX application? - [x] 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`: ```groovy // 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 ndkVersion = "20.1.5948944" playServicesVersion = "17.0.0" androidMapsUtilsVersion = "2.2.3" googlePlayServicesAuthVersion = "17.0.0" } repositories { google() jcenter() } dependencies { classpath("com.android.tools.build:gradle:4.1.0") classpath 'com.google.gms:google-services:4.3.8' // 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("$rootDir/../node_modules/react-native/android") } maven { // Android JSC is installed from npm url("$rootDir/../node_modules/jsc-android/dist") } google() jcenter() maven { url 'https://www.jitpack.io' } } } ``` #### `android/app/build.gradle`: ```groovy apply plugin: "com.android.application" apply plugin: 'com.google.gms.google-services' apply from: '../../node_modules/react-native-unimodules/gradle.groovy' 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: true, // clean and rebuild if changing ] apply from: "../../node_modules/react-native/react.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 { ndkVersion rootProject.ext.ndkVersion compileSdkVersion rootProject.ext.compileSdkVersion compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } defaultConfig { applicationId "com.prototype" minSdkVersion rootProject.ext.minSdkVersion targetSdkVersion rootProject.ext.targetSdkVersion versionCode 1 versionName "1.0" } 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' } } buildTypes { debug { signingConfig signingConfigs.debug } release { // Caution! In production, you need to generate your own keystore file. // see https://reactnative.dev/docs/signed-apk-android. signingConfig signingConfigs.debug 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 // Example: versionCode 1 will generate 1001 for armeabi-v7a, 1002 for x86, etc. 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 = defaultConfig.versionCode * 1000 + versionCodes.get(abi) } } } } dependencies { implementation fileTree(dir: "libs", include: ["*.jar"]) //noinspection GradleDynamicVersion implementation "com.facebook.react:react-native:+" // From node_modules implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.0.0" addUnimodulesDependencies() 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) { def hermesPath = "../../node_modules/hermes-engine/android/"; debugImplementation files(hermesPath + "hermes-debug.aar") releaseImplementation files(hermesPath + "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: file("../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project) ``` #### `android/settings.gradle`: ```groovy rootProject.name = 'Prototype' include ':react-native-vector-icons' project(':react-native-vector-icons').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-vector-icons/android') apply from: '../node_modules/react-native-unimodules/gradle.groovy'; includeUnimodulesProjects() apply from: file("../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesSettingsGradle(settings) include ':app' ``` #### `MainApplication.java`: ```java package com.prototype; import com.prototype.generated.BasePackageList; import android.app.Application; import android.content.Context; 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.soloader.SoLoader; import java.lang.reflect.InvocationTargetException; import java.util.List; import java.util.Arrays; import org.unimodules.adapters.react.ModuleRegistryAdapter; import org.unimodules.adapters.react.ReactModuleRegistryProvider; import org.unimodules.core.interfaces.SingletonModule; import com.facebook.react.bridge.JSIModulePackage; import com.swmansion.reanimated.ReanimatedJSIModulePackage; public class MainApplication extends Application implements ReactApplication { private final ReactModuleRegistryProvider mModuleRegistryProvider = new ReactModuleRegistryProvider(new BasePackageList().getPackageList(), null); private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) { @Override public boolean getUseDeveloperSupport() { return BuildConfig.DEBUG; } @Override protected List getPackages() { @SuppressWarnings("UnnecessaryLocalVariable") List packages = new PackageList(this).getPackages(); // Packages that cannot be autolinked yet can be added manually here, for example: // packages.add(new MyReactNativePackage()); // Add unimodules List unimodules = Arrays.asList( new ModuleRegistryAdapter(mModuleRegistryProvider) ); packages.addAll(unimodules); 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()); } /** * 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.prototype.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`: ```xml ```


Environment

Click To Expand

**`react-native info` output:** ``` System: OS: Windows 10 10.0.19043 CPU: (4) x64 Intel(R) Core(TM) i5-6600 CPU @ 3.30GHz Memory: 2.01 GB / 15.89 GB Binaries: Node: 14.16.1 - C:\Program Files\nodejs\node.EXE Yarn: 1.22.10 - ~\AppData\Roaming\npm\yarn.CMD npm: 7.18.1 - C:\Program Files\nodejs\npm.CMD Watchman: Not Found SDKs: Android SDK: Not Found Windows SDK: Not Found IDEs: Android Studio: Version 4.1.0.0 AI-201.8743.12.41.7199119 Visual Studio: Not Found Languages: Java: 11.0.10 npmPackages: @react-native-community/cli: Not Found react: ^17.0.2 => 17.0.2 react-native: ^0.64.0 => 0.64.2 react-native-windows: 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 - [x] **Android** but have not tested behavior on iOS - [ ] Both - **`react-native-firebase` version you're using that has this issue:** ``` "@react-native-firebase/app": "^12.1.0", "@react-native-firebase/auth": "^12.1.0", ``` - **`Firebase` module(s) you're using that has the issue:** - `emailVerified` - **Are you using `TypeScript`?** - `N` & `^4.2.4` - I have the package in my package.json because I created it with IntelliJ but I don't use it


mikehardy commented 3 years ago

This may be something to do with hooks. I think the best way to continue is a reproduction we can share https://stackoverflow.com/help/minimal-reproducible-example The reproduction should be a complete App.js we can drop in to the result of https://github.com/mikehardy/rnfbdemo/blob/master/make-demo.sh so we know we're operating on equivalent setups

I use email auth in my work project, and I use AppState from react-native to tell when the app goes foreground again after clicking the link, and when it comes back I re-check for email verified and it works. Just tested it yesterday.


  async componentDidMount(): Promise<void> {
    AppState.addEventListener('change', this.handleAppStateChange);
  }

  async componentWillUnmount(): Promise<void> {
    AppState.removeEventListener('change', this.handleAppStateChange);
  }

  private handleAppStateChange = async () => {
    console.log('EmailVerify::handleAppStateChange - App has changed state!');

    if (AppState.currentState === 'active' && (await this.checkVerificationEmail())) {
      console.log('EmailVerify::handleAppStateChange - user is verified, alerting and routing?');
      RX.Alert.show(
        I18NService.translate('email-verified'),
        I18NService.translate('email-verified-message')
      );
      Analytics.analyticsEvent('successEmailVerify');
    }
  };

  private checkVerificationEmail = async (): Promise<boolean> => {
    console.log('EmailVerify::checkVerificationEmail - checking verification email status');
    console.log('EmailVerify::checkVerificationEmail - auth user: ', firebase.auth().currentUser);

    const { currentUser } = firebase.auth();
    if (!currentUser) {
      RX.Alert.show(
        I18NService.translate('invalid-session'),
        I18NService.translate('invalid-session-message'),
        [
          {
            text: 'OK',
            onPress: () => {
              NavigationService.navigate('Ingresa');
            },
          },
        ]
      );
    } else {
      try {
        UserStore.addUserChangedListener();
        console.log('EmailVerify::checkVerificationEmail - Calling reload');
        await currentUser.reload();

        // You have to tack the auth() user into our state or the reload is useless...
        console.log('EmailVerify::_handleCheckVerificationEmailSilent - Called reload');
      } catch (e) {
        const { code, message } = e;
        RX.Alert.show(
          I18NService.translate('login-error'),
          I18NService.translate(code, { default: message })
        );
        console.log('EmailVerify::checkVerificationEmail - problem reloading user', e);
      }
      console.log('EmailVerify::checkVerificationEmail - auth user: ', firebase.auth().currentUser);
      return firebase.auth().currentUser?.emailVerified ?? false;
    }
    return false;
  };

Obviously there is some extraneous code in there (calls to my user store, analytics stuff) but I pasted it all in - this is the exact code that runs in my app and it works

So the burden of proof here is pretty high - I think you have a project-specific issue, or else there is something very subtle happening.

KrisLau commented 3 years ago

Will do! Also just to add more info that might be helpful: I added a button that calls reload and getIdToken(true) and displays the emailVerified property. That still didn't work but then whenever I fast refresh the app with a minor change after that it displays emailVerified as true. Weirdly enough that update only seems to effect the page that I'm doing the fast refreshing on because my navigator is also supposed to be checking the emailVerified property but it detects it as false until I fast refresh it by adding a console.log statement.

Also I'm not handling the verification in-app and I'm also not using dynamic links which might be what I test next before creating the repro,

mikehardy commented 3 years ago

I wonder if it's a difference of remote debugger or not, as well :thinking: - definitely works for me though. Good luck!

stale[bot] commented 3 years ago

Hello 👋, to help manage issues we automatically close stale issues. This issue has been automatically marked as stale because it has not had activity for quite some time. Has this issue been fixed, or does it still require the community's attention?

This issue will be closed in 15 days if no further activity occurs. Thank you for your contributions.

KrisLau commented 3 years ago

Not sure what happened but it works now even though I haven't changed anything? 🤔 It takes a second to return emailVerified as true so displaying an error is a little awkward. It would be nice if there was a way to check if an email isVerified without logging in first. Either way I'll be closing the issue and thank you for all the help!

SohelIslamImran commented 1 year ago

Same issue