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.64k stars 2.21k forks source link

emailVerified always false even after reload πŸ”₯ #3597

Closed carinlynchin closed 4 years ago

carinlynchin commented 4 years ago

Issue

:fire:

***UPDATE if NOT using dynamic links, the email verification link works fine... i do have to reload the user though. But for the life of me and all the documentation I read, I can't see why it will not verify email when trying to use dynamic links so it opens in the app after clicking on email verification.


Using dynamic Links to send email verification. I receive the email and click on it. it opens the app, and in my debuggers for onLink, I reload the user to try and get the emailVerified property. it just stays false all the time.

including screenshots: Capture Capture2

maybe i have the wrong stuff setup?

Capture3


Project Files

Javascript

Click To Expand

#### `package.json`: ```json # N/A { "name": "repropal", "version": "0.0.1", "private": true, "scripts": { "android": "react-native run-android", "ios": "react-native run-ios", "start": "react-native start", "test": "jest", "lint": "eslint ." }, "dependencies": { "@fortawesome/fontawesome-svg-core": "^1.2.28", "@fortawesome/free-brands-svg-icons": "^5.13.0", "@fortawesome/free-solid-svg-icons": "^5.13.0", "@fortawesome/react-native-fontawesome": "^0.2.4", "@react-native-community/google-signin": "^4.0.0", "@react-native-community/masked-view": "^0.1.10", "@react-native-firebase/app": "^6.7.1", "@react-native-firebase/auth": "^6.7.1", "@react-native-firebase/dynamic-links": "^6.7.1", "@react-navigation/native": "^5.1.6", "@react-navigation/stack": "^5.2.13", "react": "16.11.0", "react-native": "0.62.2", "react-native-fbsdk": "^1.1.2", "react-native-gesture-handler": "^1.6.1", "react-native-reanimated": "^1.8.0", "react-native-safe-area-context": "^0.7.3", "react-native-screens": "^2.6.0", "react-native-svg": "^12.1.0", "react-native-svg-transformer": "^0.14.3" }, "devDependencies": { "@babel/core": "^7.6.2", "@babel/runtime": "^7.6.2", "@react-native-community/eslint-config": "^0.0.5", "@react-native-firebase/functions": "^6.8.0", "babel-jest": "^24.9.0", "babel-plugin-module-resolver": "^4.0.0", "eslint": "^6.5.1", "jest": "^24.9.0", "metro": "^0.59.0", "metro-core": "^0.59.0", "metro-react-native-babel-preset": "^0.58.0", "react-test-renderer": "16.11.0" }, "jest": { "preset": "react-native" } } ``` #### `firebase.json` for react-native-firebase v6: ```json # N/A { "functions": { "predeploy": [ "npm --prefix \"$RESOURCE_DIR\" run lint", "npm --prefix \"$RESOURCE_DIR\" run build" ] } } ```

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? - [ ] my application is an AndroidX application? - [ ] I am using `android/gradle.settings` `jetifier=true` for Android compatibility? - [x ] 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 = "28.0.3" minSdkVersion = 16 compileSdkVersion = 28 targetSdkVersion = 28 } repositories { google() jcenter() mavenCentral() } dependencies { classpath('com.android.tools.build:gradle:3.6.3') classpath 'com.google.gms:google-services:4.3.3' // 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`: ``` apply plugin: "com.android.application" 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://facebook.github.io/react-native/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, // 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 { compileSdkVersion rootProject.ext.compileSdkVersion compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } defaultConfig { applicationId "com.repropal" minSdkVersion rootProject.ext.minSdkVersion targetSdkVersion rootProject.ext.targetSdkVersion versionCode 1 versionName "1.0" multiDexEnabled true } 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://facebook.github.io/react-native/docs/signed-apk-android. signingConfig signingConfigs.debug minifyEnabled enableProguardInReleaseBuilds proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro" } } packagingOptions { pickFirst "lib/armeabi-v7a/libc++_shared.so" pickFirst "lib/arm64-v8a/libc++_shared.so" pickFirst "lib/x86/libc++_shared.so" pickFirst "lib/x86_64/libc++_shared.so" } // 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 implementation 'com.google.firebase:firebase-analytics:17.2.2' implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.0.0" implementation 'com.android.support:multidex:1.0.3' implementation 'com.facebook.android:facebook-android-sdk:[5,6)' implementation 'com.google.firebase:firebase-dynamic-links:19.1.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' } 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) apply plugin: 'com.google.gms.google-services' ``` #### `android/settings.gradle`: ``` rootProject.name = 'repropal' include ':react-native-svg' project(':react-native-svg').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-svg/android') include ':react-native-svg' project(':react-native-svg').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-svg/android') apply from: file("../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesSettingsGradle(settings) include ':app' ``` #### `MainApplication.java`: ```java // N/A package com.repropal; import android.app.Application; import android.content.Context; import com.facebook.FacebookSdk; import com.facebook.appevents.AppEventsLogger; import com.facebook.react.PackageList; import com.facebook.react.ReactApplication; import com.horcrux.svg.SvgPackage; import com.horcrux.svg.SvgPackage; 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; public class MainApplication extends Application implements ReactApplication { 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()); return packages; } @Override protected String getJSMainModuleName() { return "index"; } }; @Override public ReactNativeHost getReactNativeHost() { return mReactNativeHost; } @Override public void onCreate() { super.onCreate(); SoLoader.init(this, /* native exopackage */ false); initializeFlipper(this, getReactNativeHost().getReactInstanceManager()); FacebookSdk.sdkInitialize(getApplicationContext()); AppEventsLogger.activateApp(this); } /** * 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.repropal.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`: ``` ```


Environment

Click To Expand

**`react-native info` output:** ``` System: OS: Windows 10 10.0.18363 CPU: (4) x64 Intel(R) Core(TM) i5-7600K CPU @ 3.80GHz Memory: 2.84 GB / 15.96 GB Binaries: Node: 14.0.0 - C:\Program Files\nodejs\node.EXE Yarn: 1.22.4 - C:\Users\carine\AppData\Roaming\npm\yarn.CMD npm: 6.14.4 - C:\Program Files\nodejs\npm.CMD Watchman: Not Found SDKs: Android SDK: Not Found IDEs: Android Studio: Version 3.6.0.0 AI-192.7142.36.36.6392135 Languages: Java: 1.8.0_251 - C:\Program Files\Java\jdk1.8.0_251\bin\javac.EXE Python: 2.7.17 - C:\Python27\python.EXE npmPackages: @react-native-community/cli: Not Found react: 16.11.0 => 16.11.0 react-native: 0.62.2 => 0.62.2 npmGlobalPackages: *react-native*: Not Found ``` - **Platform that you're experiencing the issue on**: - [ ] iOS - [x ] 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:** - `^6.7.1` - **`Firebase` module(s) you're using that has the issue:** - `e.g. Instance ID` - **Are you using `TypeScript`?** - `N`


carinlynchin commented 4 years ago

to simplify the issue... i removed the action url from being the dynamic link to instead being the regular link. After clicking continue...(url on browser based widget) I went back and refreshed, user still said "not verified". I cleared the cache on the app and logged in again and now it is finally verified, which makes me think there is something I did wrong with the dynamic links then. I'm not sure what though as I had tried various deep link urls to try and pin point the issue

Salakar commented 4 years ago

cc @dackers86 @russellwheatley could you try reproduce? Thanks

russellwheatley commented 4 years ago

Hey @carinlynchin, thanks for raising the issue. I assume this is your own custom verification link https://repropal.com/email-verified that the user has to "click" in order to be verified? This might seem like a silly question, but when do you actually call the email verification link? (assuming I understood its purpose).

stale[bot] commented 4 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.

tad3j commented 4 years ago

I'm experiencing the same issue in react-native app while in react web app (firebase-js-sdk) I get emailVerified = true. I'm subscribed via auth module and listener is also not triggered.

"@react-native-firebase/app": "^8.0.1",
"@react-native-firebase/auth": "^8.0.10",

When looking for emailVerified on firebase functions side, I've noticed that admin. auth. DecodedIdToken's email verified property is using different casing email_verified and not emailVerified. Wonder if this could be the issue here?

I've noticed that you use auth id token but emailVerified is already set to false here, so I assume that JS code works ok and problem may be higher in native code, specifically method firebaseUserToMap may be hydrating the value incorrectly?

There is also a TODO for isEmailVerified here: https://github.com/invertase/react-native-firebase/blob/759d67e6fbb7e05cd2fc7d532284e91ab428ca6d/packages/auth/lib/index.d.ts#L357

With some further debugging I'm noticing that user.isEmailVerified() is returning false which is part of firebase SDK, so I guess issue comes from there? Also using logcat I can see that Auth: addAuthStateListener:eventBody { NativeMap: {"user": { ... "emailVerified":false ...}}}

Can be reproduces with invertase's firebase-authentication-kit.

stale[bot] commented 4 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.

dackers86 commented 4 years ago

@mikehardy Have we established this as an upstream issue?

Happy to investigate otherwise...

mikehardy commented 4 years ago

I don't know - I didn't look to deeply @dackers86 but it might just be a mismatch between key expected to come out of upstream and key emitted here (email_verified vs emailVerified) ?

andreibarabas commented 4 years ago

hey @mikehardy . I can confirm the issue. Just upgraded to the latest 9.0 version of auth package, and the emailVerified flag is always set to false.

The email links that I receive via email are the standard ones:

https://fitclans-sandbox.firebaseapp.com/__/auth/action?mode=verifyEmail&oobCode=zjriLxi1av3qHEKwDpfWo3y0oFBO4eLuHx6HZsq7nhsAAAF0OIe16Q&apiKey=AIzaSyDNc-mhS0zytH4e1QzAEY5dmrkzpbFU1ik&lang=en

tad3j commented 4 years ago

I've updated today to the latest version and the issue seems to be gone for me. "@react-native-firebase/auth": "^9.2.1",

mikehardy commented 4 years ago

Interesting - that argues for it having been an upstream issue, one of the most recent changes was to bump the upstream pod dependency (for ios) and bom (for android) that we reference

dackers86 commented 4 years ago

Closing as this seems a viable fix for this issue

jordynchuhaloff commented 3 years ago

Hi @mikehardy, we're experiencing this issue as well. We are on @react-native-firebase/auth version 9.2.7.

The non-dynamic link works for us - emailVerified is set to true (after we reload the Firebase user).

If I change nothing except to make it a dynamic link (by adding handleCodeInApp: true to sendEmailVerification), clicking the link in the email takes me back to the app, but emailVerified is not set to true, even after a reload. I verified that all of the same code is being called (onLink is called, the user is reloaded), but emailVerified remains false.

Is something happening on the 'You have been verified' page that is skipped when linking straight to the app?

I'll add example links from both scenarios.


Non-dynamic link (goes to Firebase page with β€˜You have been verified’ + continue button)

https://[PROJECT].firebaseapp.com/__/auth/action?mode=verifyEmail&oobCode=[OOB_CODE]&apiKey=[API_KEY]&continueUrl=https%3A%2F%2F[DOMAIN].page.link%3Flink%3Dhttps%3A%2F%2F[DOMAIN]..page.link%2Femail-verification%26apn%3Dio.[EXAMPLE].testnet%26amv%26ibi%3Dio..[EXAMPLE].testnet%26ifl%3Dhttps%3A%2F%2F[DOMAIN].page.link%2Femail-verification&lang=en


Dynamic link (goes straight into the app)

https://[DOMAIN].page.link/?link=https://[PROJECT].firebaseapp.com/__/auth/action?apiKey%3D[API_KEY]%26mode%3DverifyEmail%26oobCode%3D[OOB_CODE]%26continueUrl%3Dhttps://[DOMAIN].page.link/email-verification%26lang%3Den&apn=io.[EXAMPLE].testnet&amv&ibi=io.[EXAMPLE].testnet&ifl=https://[PROJECT].firebaseapp.com/__/auth/action?apiKey%3D[API_KEY]%26mode%3DverifyEmail%26oobCode%3D[OOB_CODE]%26continueUrl%3Dhttps://[DOMAIN].page.link/email-verification%26lang%3Den

mikehardy commented 3 years ago

I believe the app is responsible for completing the sign-in when you handle in app https://firebase.google.com/docs/auth/web/email-link-auth#completing_sign-in_in_a_mobile_app

jordynchuhaloff commented 3 years ago

Ah, yes, that's true for sign-in (we're also using that feature).

I was having trouble with email verification (adding an email to a user).

You set me on the right track though, and it turns out you need to handle email verification in app as well! I just needed to parse the oobCode from the incoming dynamic link and then call applyActionCode(oobCode);

It's working now, thank you!

danloiterton commented 3 years ago

Ah, yes, that's true for sign-in (we're also using that feature).

I was having trouble with email verification (adding an email to a user).

You set me on the right track though, and it turns out you need to handle email verification in app as well! I just needed to parse the oobCode from the incoming dynamic link and then call applyActionCode(oobCode);

It's working now, thank you!

Having the same exact issue. How did you get the oobCode? Did you just extract it manually from the dynamic link's url? Or is there a function/property somewhere I'm missing?

jordynchuhaloff commented 3 years ago

I didn't see a Firebase function to use, so I got the oobCocde manually from the link. Like this:

// helper to get oobCode
const getURLParam = (urlString: string, param: string) => {
  const url = new URL(urlString);
  const params = new URLSearchParams(url.search);

  return params.get(param) || "";
};

// called when we detect an incoming link, using `dynamicLinks().onLink()`
const confirmEmailVerification = (url: string) => {
    const oobCode = getURLParam(url, "oobCode");

    return auth()
      .applyActionCode(oobCode)
      .then(() => {
        // reload Firebase user
      })
      .catch((error) => {
        throw `We had trouble verifying your email. Please try again.`;
      });
  },
);
danloiterton commented 3 years ago

URL and URLSearchParams don't seem to work on iOS in react native without polyfills (this issue seems to be persisting still). So I just wrote my own url parser.

However, your posts finally got me on the right track (after days of hair-pulling). So many thanks for that! πŸ™ πŸ™Œ πŸ‘Š

Following ALL these steps got me there in the end (what a pain this was!):

  1. sign the user up with const creds = await auth().createUserWithEmailAndPassword(email, password)
  2. send the verification email with creds.user.sendEmailVerification(actionCodeSettings)
  3. click the link in the email --> automatically opens the app (if actionCodeSettings are correct and dynamic links are set up properly)
  4. handle incoming dynamic links with dynamicLinks.onLink(handleLink) and also with dynamicLinks.getInitialLink().then((link) => link && handleDynamicLink(link)) (in case the app isn't running when the link is clicked)
  5. in the handler, parse the link.url to extract the url params mode and oobCode
  6. if mode === 'verifyEmail', apply the action code with await auth().applyActionCode(oobCode)
  7. this will NOT trigger a state change, so listeners on auth().onAuthStateChanged() will not fire. So you must call await auth().currentUser.reload(). This will not trigger a state change either, but...
  8. finally, auth().currentUser.emailVerified === true! Hooray!
  9. go and make yourself a very strong drink (yay for working from home) πŸ₯ƒ
jordynchuhaloff commented 3 years ago

Ya, we added a polyfill for ours:

import { URL, URLSearchParams } from "whatwg-url";
global.URL = URL;
global.URLSearchParams = URLSearchParams;

I can definitely relate to the hair-pulling. Had quite a bit of that myself when implementing dynamic links. Glad these posts helped you out! πŸ₯‚

nanreh-dev commented 2 years ago

Hi!, in 15.2.0 version i have same emailVerified false issue, but, when it asks me (on mobile browser) whether to open with the app or with chrome, if i choose to open the app directly, emailVerified it is still false regardless of whether I reload the user, but, if I choose to open in chrome, it verifies and when I press continue it redirects me to the app and emailVerified Is true. The question is: how do I make it always open in a browser? Ok, at least for me the solution was to set handleCodeInApp to false, in this way it will always open in the browser and when the continue button is pressed it redirects me to the app

izakfilmalter commented 2 years ago

URL and URLSearchParams don't seem to work on iOS in react native without polyfills (this issue seems to be persisting still). So I just wrote my own url parser.

However, your posts finally got me on the right track (after days of hair-pulling). So many thanks for that! πŸ™ πŸ™Œ πŸ‘Š

Following ALL these steps got me there in the end (what a pain this was!):

  1. sign the user up with const creds = await auth().createUserWithEmailAndPassword(email, password)
  2. send the verification email with creds.user.sendEmailVerification(actionCodeSettings)
  3. click the link in the email --> automatically opens the app (if actionCodeSettings are correct and dynamic links are set up properly)
  4. handle incoming dynamic links with dynamicLinks.onLink(handleLink) and also with dynamicLinks.getInitialLink().then((link) => link && handleDynamicLink(link)) (in case the app isn't running when the link is clicked)
  5. in the handler, parse the link.url to extract the url params mode and oobCode
  6. if mode === 'verifyEmail', apply the action code with await auth().applyActionCode(oobCode)
  7. this will NOT trigger a state change, so listeners on auth().onAuthStateChanged() will not fire. So you must call await auth().currentUser.reload(). This will not trigger a state change either, but...
  8. finally, auth().currentUser.emailVerified === true! Hooray!
  9. go and make yourself a very strong drink (yay for working from home) πŸ₯ƒ

This is gold. Needs to be added to the docs. So much time wasted on this.

mikehardy commented 2 years ago

Hey @izakfilmalter :wave:

Needs to be added to the docs

We merge all reasonable PRs and the GitHub web UI flow is really easy, just hit the edit button on the top of any page

Thanks!

izakfilmalter commented 2 years ago

Ya, I will put this on my todo list.

GunnarAK commented 2 years ago

To add to @danloiterton 's comment: Replace auth().onAuthStateChanged() for auth().onUserChanged() which does listen to changes such as emailVerified.

Docs: https://rnfirebase.io/reference/auth#onUserChanged

mikehardy commented 2 years ago

Yes - the problem with that one is that it is useful but not web compatible. To handle web as well (for instance: https://github.com/invertase/react-native-firebase-authentication-example) you need to have a way for the user to imperatively declare (like via a dialog): I have confirmed the email, please recheck) at which point you should reload the user and re-check the flag.

I also have an AppState listener in native so that when I am on the "verify your email" screen that sends the email, meaning you expect to go into background as the user switches to their email app, I re-load + re-check when the AppState comes back to foreground (because they probably verified their email, right?) and I re-load user + re-check the flag.

But onUserChanged is quite convenient native.

There are quite a few ways to do this, basically, I do them all ;-)