From 2669b7f1adecdad80b9af7d44d8a0e2f8592c78b Mon Sep 17 00:00:00 2001 From: Nick Williams Date: Sat, 31 Oct 2026 04:33:49 +0000 Subject: [PATCH 1/4] Align the Auth API with the Firebase Android SDK Every public Auth class and member the Android SDK declares and this port lacked is added, and the four places where the port's shape differed are aligned, so that code written against the Android SDK compiles and links against this one: FirebaseUser.getPhotoUrl returns a Uri, FirebaseUser implements the UserInfo interface (which gains isEmailVerified), the ActionCodeInfo types are classes, and the profile change request exposes its display name and photo URI. AuthResult gains getAdditionalUserInfo and getCredential, filled from the sign-in response. The providers expose their PROVIDER_ID and sign-in method constants and create the Android credential types, including EmailAuthCredential for a password or a sign-in link, which signInWithCredential and linkWithCredential accept. OAuthCredential is the Android abstract class over a package-private implementation, OAuthProvider extends FederatedAuthProvider and its builders expose their state. ActionCodeSettings is implemented and travels with every action email, and ActionCodeUrl parses an action link, unwrapping a Dynamic Link. FirebaseAuth gains sendPasswordResetEmail, sendSignInLinkToEmail, signInWithEmailLink, isSignInWithEmailLink, checkActionCode, verifyPasswordResetCode, confirmPasswordReset, applyActionCode, fetchSignInMethodsForEmail, updateCurrentUser, revokeAccessToken, the language code (sent as X-Firebase-Locale), useAppLanguage, the tenant id, the custom auth domain, getFirebaseAuthSettings, getPendingAuthResult and initializeRecaptchaConfig; FirebaseUser gains sendEmailVerification, updatePhoneNumber(PhoneAuthCredential), verifyBeforeUpdateEmail(String) and getTenantId. PhoneAuthOptions, the multi-factor info, assertion and generator types, TotpSecret, FirebaseAuthSettings, FirebaseAuthProvider and the exception members (FirebaseAuthUserCollisionException's email and credential, FirebaseAuthWeakPasswordException's reason, FirebaseAuthMultiFactorException's resolver, FirebaseAuthMissingActivityForRecaptchaException) complete the surface; what needs a device or a browser (phone verification, multi-factor, Activity flows) is present and fails with a clear message. FirebaseAuthApiTest covers the shapes without a server and FirebaseAuthEmailFlowsTest runs the action-code flows against the Auth emulator; the README describes what the port now supports. --- README.md | 23 +- firebase-debug.log | 50 ++++ .../firebase/auth/ActionCodeEmailInfo.java | 13 +- .../google/firebase/auth/ActionCodeInfo.java | 19 +- .../auth/ActionCodeMultiFactorInfo.java | 9 +- .../firebase/auth/ActionCodeResult.java | 19 +- .../firebase/auth/ActionCodeResultImpl.kt | 47 ++++ .../firebase/auth/ActionCodeSettings.kt | 98 +++++++ .../com/google/firebase/auth/ActionCodeUrl.kt | 51 ++++ .../firebase/auth/AdditionalUserInfo.java | 13 + .../google/firebase/auth/AuthCredential.java | 60 ++-- .../com/google/firebase/auth/AuthResult.java | 4 + .../google/firebase/auth/AuthResultImpl.kt | 76 +++++ .../firebase/auth/EmailAuthCredential.java | 36 +++ .../firebase/auth/EmailAuthProvider.java | 20 +- .../firebase/auth/FacebookAuthCredential.java | 24 ++ .../firebase/auth/FacebookAuthProvider.java | 10 +- .../firebase/auth/FederatedAuthProvider.java | 7 + .../com/google/firebase/auth/FirebaseAuth.kt | 261 +++++++++++++++--- ...uthMissingActivityForRecaptchaException.kt | 5 + .../auth/FirebaseAuthMultiFactorException.kt | 9 + .../firebase/auth/FirebaseAuthProvider.java | 5 + .../firebase/auth/FirebaseAuthSettings.java | 13 + .../FirebaseAuthUserCollisionException.kt | 16 +- .../auth/FirebaseAuthWeakPasswordException.kt | 11 +- .../com/google/firebase/auth/FirebaseUser.kt | 56 ++-- .../firebase/auth/GithubAuthCredential.java | 24 ++ .../firebase/auth/GithubAuthProvider.java | 10 +- .../firebase/auth/GoogleAuthCredential.java | 30 +- .../com/google/firebase/auth/MultiFactor.kt | 135 +++++++++ .../google/firebase/auth/OAuthCredential.java | 29 +- .../firebase/auth/OAuthCredentialImpl.java | 51 ++++ .../google/firebase/auth/OAuthProvider.java | 28 +- .../firebase/auth/PhoneAuthCredential.kt | 18 ++ .../google/firebase/auth/PhoneAuthOptions.kt | 63 +++++ .../firebase/auth/PhoneAuthProvider.java | 42 --- .../google/firebase/auth/PhoneAuthProvider.kt | 73 +++++ .../java/com/google/firebase/auth/Stubs.kt | 79 +----- .../firebase/auth/TwitterAuthCredential.java | 31 +++ .../firebase/auth/TwitterAuthProvider.java | 12 +- .../java/com/google/firebase/auth/UserInfo.kt | 26 ++ .../firebase/auth/UserProfileChangeRequest.kt | 8 +- src/test/kotlin/FirebaseAuthApiTest.kt | 218 +++++++++++++++ src/test/kotlin/FirebaseAuthEmailFlowsTest.kt | 124 +++++++++ src/test/kotlin/FirebaseAuthTest.kt | 2 +- 45 files changed, 1717 insertions(+), 241 deletions(-) create mode 100644 firebase-debug.log create mode 100644 src/main/java/com/google/firebase/auth/ActionCodeResultImpl.kt create mode 100644 src/main/java/com/google/firebase/auth/ActionCodeSettings.kt create mode 100644 src/main/java/com/google/firebase/auth/ActionCodeUrl.kt create mode 100644 src/main/java/com/google/firebase/auth/AdditionalUserInfo.java create mode 100644 src/main/java/com/google/firebase/auth/AuthResultImpl.kt create mode 100644 src/main/java/com/google/firebase/auth/EmailAuthCredential.java create mode 100644 src/main/java/com/google/firebase/auth/FacebookAuthCredential.java create mode 100644 src/main/java/com/google/firebase/auth/FederatedAuthProvider.java create mode 100644 src/main/java/com/google/firebase/auth/FirebaseAuthMissingActivityForRecaptchaException.kt create mode 100644 src/main/java/com/google/firebase/auth/FirebaseAuthMultiFactorException.kt create mode 100644 src/main/java/com/google/firebase/auth/FirebaseAuthProvider.java create mode 100644 src/main/java/com/google/firebase/auth/FirebaseAuthSettings.java create mode 100644 src/main/java/com/google/firebase/auth/GithubAuthCredential.java create mode 100644 src/main/java/com/google/firebase/auth/MultiFactor.kt create mode 100644 src/main/java/com/google/firebase/auth/OAuthCredentialImpl.java create mode 100644 src/main/java/com/google/firebase/auth/PhoneAuthCredential.kt create mode 100644 src/main/java/com/google/firebase/auth/PhoneAuthOptions.kt delete mode 100644 src/main/java/com/google/firebase/auth/PhoneAuthProvider.java create mode 100644 src/main/java/com/google/firebase/auth/PhoneAuthProvider.kt create mode 100644 src/main/java/com/google/firebase/auth/TwitterAuthCredential.java create mode 100644 src/main/java/com/google/firebase/auth/UserInfo.kt create mode 100644 src/test/kotlin/FirebaseAuthApiTest.kt create mode 100644 src/test/kotlin/FirebaseAuthEmailFlowsTest.kt diff --git a/README.md b/README.md index 6c8d38d..829ad13 100644 --- a/README.md +++ b/README.md @@ -140,19 +140,16 @@ Is the Firebase library or API you need missing? [Create an issue](https://githu Currently, the following limitations are observed: -#### Firebase Auth implementation is minimal and only supports a small subset of the API: - - `createUserWithEmailAndPassword` - - `signInAnonymously` - - `signInWithCustomToken` - - `signInWithEmailAndPassword` - - `currentUser` - - `getAccessToken` - - `getUid` - - `addIdTokenListener` - - `removeIdTokenListener` - - `addAuthStateListener` - - `removeAuthStateListener` - - `signOut` +#### Firebase Auth is a REST implementation and does not cover the whole Android API: +Supported: anonymous, email and password, custom token, email link and credential sign-in (Google, Facebook, GitHub, +Twitter, a generic OAuth provider, a phone verification code), linking a credential, profile, email and phone number +updates, password reset, email verification and the other action-code flows, sign-in method lookup, token refresh and +the auth state and ID token listeners. + +Not supported, as they need a device or a browser: phone number verification (`PhoneAuthProvider.verifyPhoneNumber` +reports a failure to its callbacks), multi-factor enrolment and sign-in, provider sign-in through an Activity +(`startActivityForSignInWithProvider` and the `FirebaseUser` counterparts fail) and reCAPTCHA. Not yet implemented: +`reauthenticate`, `reauthenticateAndRetrieveData`, `unlink` and `updatePassword`. #### Realtime Database does not support [Disk Persistence](https://firebase.google.com/docs/database/android/offline-capabilities), and should be setup as follows: ```java FirebaseDatabase.getInstance().setPersistenceEnabled(false) diff --git a/firebase-debug.log b/firebase-debug.log new file mode 100644 index 0000000..216ed43 --- /dev/null +++ b/firebase-debug.log @@ -0,0 +1,50 @@ +[debug] [2026-10-31T04:31:58.246Z] ---------------------------------------------------------------------- +[debug] [2026-10-31T04:31:58.248Z] Command: /opt/node22/bin/node /opt/node22/bin/firebase emulators:start --project fir-java-sdk --import=src/test/resources/firebase_data +[debug] [2026-10-31T04:31:58.248Z] CLI Version: 14.27.0 +[debug] [2026-10-31T04:31:58.249Z] Platform: linux +[debug] [2026-10-31T04:31:58.249Z] Node Version: v22.22.2 +[debug] [2026-10-31T04:31:58.249Z] Time: Sat Oct 31 2026 04:31:58 GMT+0000 (Coordinated Universal Time) +[debug] [2026-10-31T04:31:58.249Z] ---------------------------------------------------------------------- +[debug] +[debug] [2026-10-31T04:31:58.462Z] > command requires scopes: ["email","openid","https://www.googleapis.com/auth/cloudplatformprojects.readonly","https://www.googleapis.com/auth/firebase","https://www.googleapis.com/auth/cloud-platform"] +[debug] Failed to authenticate, have you run firebase login? +[warn] ⚠ emulators: You are not currently authenticated so some features may not work correctly. Please run firebase login to authenticate the CLI. +[info] i emulators: Starting emulators: auth {"metadata":{"emulator":{"name":"hub"},"message":"Starting emulators: auth"}} +[warn] ⚠ hub: Error when trying to check port 4400 on ::1: Error: listen EAFNOSUPPORT: address family not supported ::1:4400 {"metadata":{"emulator":{"name":"hub"},"message":"Error when trying to check port 4400 on ::1: Error: listen EAFNOSUPPORT: address family not supported ::1:4400"}} +[warn] ⚠ hub: Port 4400 is available on 127.0.0.1 but not ::1. This may cause issues with some clients. {"metadata":{"emulator":{"name":"hub"},"message":"Port 4400 is available on 127.0.0.1 but not ::1. This may cause issues with some clients."}} +[warn] ⚠ hub: If you encounter connectivity issues, consider switching to a different port or explicitly specifying "host": "" instead of hostname in firebase.json {"metadata":{"emulator":{"name":"hub"},"message":"If you encounter connectivity issues, consider switching to a different port or explicitly specifying \"host\": \"\" instead of hostname in firebase.json"}} +[warn] ⚠ ui: Error when trying to check port 4000 on ::1: Error: listen EAFNOSUPPORT: address family not supported ::1:4000 {"metadata":{"emulator":{"name":"ui"},"message":"Error when trying to check port 4000 on ::1: Error: listen EAFNOSUPPORT: address family not supported ::1:4000"}} +[warn] ⚠ ui: Port 4000 is available on 127.0.0.1 but not ::1. This may cause issues with some clients. {"metadata":{"emulator":{"name":"ui"},"message":"Port 4000 is available on 127.0.0.1 but not ::1. This may cause issues with some clients."}} +[warn] ⚠ ui: If you encounter connectivity issues, consider switching to a different port or explicitly specifying "host": "" instead of hostname in firebase.json {"metadata":{"emulator":{"name":"ui"},"message":"If you encounter connectivity issues, consider switching to a different port or explicitly specifying \"host\": \"\" instead of hostname in firebase.json"}} +[warn] ⚠ logging: Error when trying to check port 4500 on ::1: Error: listen EAFNOSUPPORT: address family not supported ::1:4500 {"metadata":{"emulator":{"name":"logging"},"message":"Error when trying to check port 4500 on ::1: Error: listen EAFNOSUPPORT: address family not supported ::1:4500"}} +[warn] ⚠ logging: Port 4500 is available on 127.0.0.1 but not ::1. This may cause issues with some clients. {"metadata":{"emulator":{"name":"logging"},"message":"Port 4500 is available on 127.0.0.1 but not ::1. This may cause issues with some clients."}} +[warn] ⚠ logging: If you encounter connectivity issues, consider switching to a different port or explicitly specifying "host": "" instead of hostname in firebase.json {"metadata":{"emulator":{"name":"logging"},"message":"If you encounter connectivity issues, consider switching to a different port or explicitly specifying \"host\": \"\" instead of hostname in firebase.json"}} +[warn] ⚠ auth: Error when trying to check port 9099 on ::1: Error: listen EAFNOSUPPORT: address family not supported ::1:9099 {"metadata":{"emulator":{"name":"auth"},"message":"Error when trying to check port 9099 on ::1: Error: listen EAFNOSUPPORT: address family not supported ::1:9099"}} +[warn] ⚠ auth: Port 9099 is available on 127.0.0.1 but not ::1. This may cause issues with some clients. {"metadata":{"emulator":{"name":"auth"},"message":"Port 9099 is available on 127.0.0.1 but not ::1. This may cause issues with some clients."}} +[warn] ⚠ auth: If you encounter connectivity issues, consider switching to a different port or explicitly specifying "host": "" instead of hostname in firebase.json {"metadata":{"emulator":{"name":"auth"},"message":"If you encounter connectivity issues, consider switching to a different port or explicitly specifying \"host\": \"\" instead of hostname in firebase.json"}} +[debug] [2026-10-31T04:32:01.556Z] assigned listening specs for emulators {"user":{"hub":[{"address":"127.0.0.1","family":"IPv4","port":4400}],"ui":[{"address":"127.0.0.1","family":"IPv4","port":4000}],"logging":[{"address":"127.0.0.1","family":"IPv4","port":4500}],"auth":[{"address":"127.0.0.1","family":"IPv4","port":9099}]},"metadata":{"message":"assigned listening specs for emulators"}} +[debug] [2026-10-31T04:32:01.559Z] Emulator locator file path: /tmp/hub-fir-java-sdk.json +[debug] [2026-10-31T04:32:01.560Z] [hub] writing locator at /tmp/hub-fir-java-sdk.json +[info] i auth: Importing config from /home/user/firebase-java-sdk/src/test/resources/firebase_data/auth_export/config.json {"metadata":{"emulator":{"name":"auth"},"message":"Importing config from /home/user/firebase-java-sdk/src/test/resources/firebase_data/auth_export/config.json"}} +[info] i auth: Importing accounts from /home/user/firebase-java-sdk/src/test/resources/firebase_data/auth_export/accounts.json {"metadata":{"emulator":{"name":"auth"},"message":"Importing accounts from /home/user/firebase-java-sdk/src/test/resources/firebase_data/auth_export/accounts.json"}} +[debug] [2026-10-31T04:32:07.953Z] Could not find VSCode notification endpoint: FetchError: request to http://localhost:40001/vscode/notify failed, reason: connect ECONNREFUSED 127.0.0.1:40001. If you are not running the Firebase Data Connect VSCode extension, this is expected and not an issue. +[info] +┌─────────────────────────────────────────────────────────────┐ +│ ✔ All emulators ready! It is now safe to connect your app. │ +│ i View Emulator UI at http://127.0.0.1:4000/ │ +└─────────────────────────────────────────────────────────────┘ + +┌────────────────┬────────────────┬────────────────────────────┐ +│ Emulator │ Host:Port │ View in Emulator UI │ +├────────────────┼────────────────┼────────────────────────────┤ +│ Authentication │ 127.0.0.1:9099 │ http://127.0.0.1:4000/auth │ +└────────────────┴────────────────┴────────────────────────────┘ + Emulator Hub host: 127.0.0.1 port: 4400 + Other reserved ports: 4500 + +Issues? Report them at https://github.com/firebase/firebase-tools/issues and attach the *-debug.log files. + +[info] i To reset the password for flows11268416-7f81-477e-a8d3-59e618ae08fb@example.com, follow this link: http://127.0.0.1:9099/emulator/action?mode=resetPassword&lang=en&oobCode=SXo-vbmm9JyHujIjtU3vgBE6KW52ecIgQYqpCUM55KktK_I9hq2AL8&apiKey=fake-api-key&newPassword=NEW_PASSWORD_HERE {"metadata":{"emulator":{"name":"auth"},"message":"To reset the password for flows11268416-7f81-477e-a8d3-59e618ae08fb@example.com, follow this link: http://127.0.0.1:9099/emulator/action?mode=resetPassword&lang=en&oobCode=SXo-vbmm9JyHujIjtU3vgBE6KW52ecIgQYqpCUM55KktK_I9hq2AL8&apiKey=fake-api-key&newPassword=NEW_PASSWORD_HERE"}} +[warn] ⚠ canHandleCodeInApp is unsupported in Auth Emulator. All OOB operations will complete via web. {"metadata":{"emulator":{"name":"auth"},"message":"canHandleCodeInApp is unsupported in Auth Emulator. All OOB operations will complete via web."}} +[info] i To sign in as flowsebf01040-fbab-427e-adcc-64a3a463a02b@example.com, follow this link: http://127.0.0.1:9099/emulator/action?mode=signIn&lang=en&oobCode=BE4aKRNHuyQBp35NeQZHuXxUHszv08tZPjiYgG1ks1dg6CyE0dPHkw&apiKey=fake-api-key&continueUrl=https%3A%2F%2Fexample.com%2Ffinish {"metadata":{"emulator":{"name":"auth"},"message":"To sign in as flowsebf01040-fbab-427e-adcc-64a3a463a02b@example.com, follow this link: http://127.0.0.1:9099/emulator/action?mode=signIn&lang=en&oobCode=BE4aKRNHuyQBp35NeQZHuXxUHszv08tZPjiYgG1ks1dg6CyE0dPHkw&apiKey=fake-api-key&continueUrl=https%3A%2F%2Fexample.com%2Ffinish"}} +[info] i To verify the email address flows2ffd184d-1380-4bf9-8fb1-2295e23573c7@example.com, follow this link: http://127.0.0.1:9099/emulator/action?mode=verifyEmail&lang=en&oobCode=KGaKIl2dWWe64lQRsiTjebIP28bMIoHAuSduQje7Y65dw2GsyRLfOz&apiKey=fake-api-key {"metadata":{"emulator":{"name":"auth"},"message":"To verify the email address flows2ffd184d-1380-4bf9-8fb1-2295e23573c7@example.com, follow this link: http://127.0.0.1:9099/emulator/action?mode=verifyEmail&lang=en&oobCode=KGaKIl2dWWe64lQRsiTjebIP28bMIoHAuSduQje7Y65dw2GsyRLfOz&apiKey=fake-api-key"}} diff --git a/src/main/java/com/google/firebase/auth/ActionCodeEmailInfo.java b/src/main/java/com/google/firebase/auth/ActionCodeEmailInfo.java index 6f47d0b..6520ff5 100644 --- a/src/main/java/com/google/firebase/auth/ActionCodeEmailInfo.java +++ b/src/main/java/com/google/firebase/auth/ActionCodeEmailInfo.java @@ -1,6 +1,13 @@ package com.google.firebase.auth; -public interface ActionCodeEmailInfo extends ActionCodeInfo { - String getPreviousEmail(); +/** The two addresses of an email change action: {@link #getEmail()} the address after it, {@link #getPreviousEmail()} before. */ +public abstract class ActionCodeEmailInfo extends ActionCodeInfo { + public ActionCodeEmailInfo() { + } -} \ No newline at end of file + ActionCodeEmailInfo(String email) { + super(email); + } + + public abstract String getPreviousEmail(); +} diff --git a/src/main/java/com/google/firebase/auth/ActionCodeInfo.java b/src/main/java/com/google/firebase/auth/ActionCodeInfo.java index 2dbb2ac..46df634 100644 --- a/src/main/java/com/google/firebase/auth/ActionCodeInfo.java +++ b/src/main/java/com/google/firebase/auth/ActionCodeInfo.java @@ -1,8 +1,17 @@ package com.google.firebase.auth; -import androidx.annotation.NonNull; +/** The account an action code concerns, from {@link FirebaseAuth#checkActionCode}. */ +public class ActionCodeInfo { + protected String email; -public interface ActionCodeInfo { - @NonNull - String getEmail(); -} \ No newline at end of file + public ActionCodeInfo() { + } + + ActionCodeInfo(String email) { + this.email = email; + } + + public String getEmail() { + return email; + } +} diff --git a/src/main/java/com/google/firebase/auth/ActionCodeMultiFactorInfo.java b/src/main/java/com/google/firebase/auth/ActionCodeMultiFactorInfo.java index 22833e8..1399e73 100644 --- a/src/main/java/com/google/firebase/auth/ActionCodeMultiFactorInfo.java +++ b/src/main/java/com/google/firebase/auth/ActionCodeMultiFactorInfo.java @@ -1,5 +1,8 @@ package com.google.firebase.auth; -public interface ActionCodeMultiFactorInfo extends ActionCodeInfo { - MultiFactorInfo getMultiFactorInfo(); -} \ No newline at end of file +public abstract class ActionCodeMultiFactorInfo extends ActionCodeInfo { + public ActionCodeMultiFactorInfo() { + } + + public abstract MultiFactorInfo getMultiFactorInfo(); +} diff --git a/src/main/java/com/google/firebase/auth/ActionCodeResult.java b/src/main/java/com/google/firebase/auth/ActionCodeResult.java index 1d115a8..7e9c12c 100644 --- a/src/main/java/com/google/firebase/auth/ActionCodeResult.java +++ b/src/main/java/com/google/firebase/auth/ActionCodeResult.java @@ -1,5 +1,8 @@ package com.google.firebase.auth; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; + public interface ActionCodeResult { int PASSWORD_RESET = 0; int VERIFY_EMAIL = 1; @@ -8,10 +11,24 @@ public interface ActionCodeResult { int SIGN_IN_WITH_EMAIL_LINK = 4; int VERIFY_BEFORE_CHANGE_EMAIL = 5; int REVERT_SECOND_FACTOR_ADDITION = 6; + int EMAIL = 0; int FROM_EMAIL = 1; + @Retention(RetentionPolicy.SOURCE) + @interface Operation { + } + + @Retention(RetentionPolicy.SOURCE) + @interface ActionDataKey { + } + + @Operation int getOperation(); ActionCodeInfo getInfo(); -} \ No newline at end of file + + /** @deprecated use {@link #getInfo()}. */ + @Deprecated + String getData(@ActionDataKey int key); +} diff --git a/src/main/java/com/google/firebase/auth/ActionCodeResultImpl.kt b/src/main/java/com/google/firebase/auth/ActionCodeResultImpl.kt new file mode 100644 index 0000000..be0cb72 --- /dev/null +++ b/src/main/java/com/google/firebase/auth/ActionCodeResultImpl.kt @@ -0,0 +1,47 @@ +package com.google.firebase.auth + +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.contentOrNull +import kotlinx.serialization.json.jsonPrimitive + +/** The result of `accounts:resetPassword` called with a code alone: its `requestType` and the account it concerns. */ +internal class ActionCodeResultImpl(data: JsonObject) : ActionCodeResult { + private val operation: Int = + when (data["requestType"]?.jsonPrimitive?.contentOrNull) { + "PASSWORD_RESET" -> ActionCodeResult.PASSWORD_RESET + "VERIFY_EMAIL" -> ActionCodeResult.VERIFY_EMAIL + "RECOVER_EMAIL" -> ActionCodeResult.RECOVER_EMAIL + "EMAIL_SIGNIN" -> ActionCodeResult.SIGN_IN_WITH_EMAIL_LINK + "VERIFY_AND_CHANGE_EMAIL" -> ActionCodeResult.VERIFY_BEFORE_CHANGE_EMAIL + "REVERT_SECOND_FACTOR_ADDITION" -> ActionCodeResult.REVERT_SECOND_FACTOR_ADDITION + else -> ActionCodeResult.ERROR + } + + private val email = data["email"]?.jsonPrimitive?.contentOrNull + private val newEmail = data["newEmail"]?.jsonPrimitive?.contentOrNull + + private val info: ActionCodeInfo? = + when (operation) { + // Recovering restores `email`; the address being left is `newEmail`. + ActionCodeResult.RECOVER_EMAIL -> EmailInfo(email, newEmail) + ActionCodeResult.VERIFY_BEFORE_CHANGE_EMAIL -> EmailInfo(newEmail, email) + ActionCodeResult.ERROR -> null + else -> email?.let { ActionCodeInfo(it) } + } + + override fun getOperation(): Int = operation + + override fun getInfo(): ActionCodeInfo? = info + + @Deprecated("Use getInfo()") + override fun getData(key: Int): String? = + when (key) { + ActionCodeResult.EMAIL -> info?.email + ActionCodeResult.FROM_EMAIL -> (info as? ActionCodeEmailInfo)?.previousEmail + else -> null + } + + private class EmailInfo(email: String?, private val previousEmail: String?) : ActionCodeEmailInfo(email) { + override fun getPreviousEmail(): String? = previousEmail + } +} diff --git a/src/main/java/com/google/firebase/auth/ActionCodeSettings.kt b/src/main/java/com/google/firebase/auth/ActionCodeSettings.kt new file mode 100644 index 0000000..e65183a --- /dev/null +++ b/src/main/java/com/google/firebase/auth/ActionCodeSettings.kt @@ -0,0 +1,98 @@ +package com.google.firebase.auth + +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.JsonPrimitive + +/** + * Where the link in an action email leads and how the app receives it, mirroring the Android class; sent with + * `sendOobCode` as its continue URL, bundle ids and link domain. + */ +class ActionCodeSettings private constructor( + private val url: String, + private val iOSBundleId: String?, + private val androidPackageName: String?, + private val androidInstallApp: Boolean, + private val androidMinimumVersion: String?, + private val handleCodeInApp: Boolean, + private val linkDomain: String?, + private val dynamicLinkDomain: String? +) { + fun getUrl(): String = url + + fun getIOSBundle(): String? = iOSBundleId + + fun getAndroidPackageName(): String? = androidPackageName + + fun getAndroidInstallApp(): Boolean = androidInstallApp + + fun getAndroidMinimumVersion(): String? = androidMinimumVersion + + fun canHandleCodeInApp(): Boolean = handleCodeInApp + + fun getLinkDomain(): String? = linkDomain + + /** The `sendOobCode` request fields these settings add. */ + internal fun toRequestFields(): Map = + buildMap { + put("continueUrl", JsonPrimitive(url)) + put("canHandleCodeInApp", JsonPrimitive(handleCodeInApp)) + iOSBundleId?.let { put("iOSBundleId", JsonPrimitive(it)) } + androidPackageName?.let { + put("androidPackageName", JsonPrimitive(it)) + put("androidInstallApp", JsonPrimitive(androidInstallApp)) + androidMinimumVersion?.let { version -> put("androidMinimumVersion", JsonPrimitive(version)) } + } + linkDomain?.let { put("linkDomain", JsonPrimitive(it)) } + dynamicLinkDomain?.let { put("dynamicLinkDomain", JsonPrimitive(it)) } + } + + class Builder internal constructor() { + private var url: String? = null + private var iOSBundleId: String? = null + private var androidPackageName: String? = null + private var androidInstallApp: Boolean = false + private var androidMinimumVersion: String? = null + private var handleCodeInApp: Boolean = false + private var linkDomain: String? = null + private var dynamicLinkDomain: String? = null + + fun setUrl(url: String): Builder = apply { this.url = url } + + fun getUrl(): String? = url + + fun setIOSBundleId(iOSBundleId: String): Builder = apply { this.iOSBundleId = iOSBundleId } + + fun getIOSBundleId(): String? = iOSBundleId + + fun setAndroidPackageName(androidPackageName: String, installIfNotAvailable: Boolean, minimumVersion: String?): Builder = apply { + this.androidPackageName = androidPackageName + this.androidInstallApp = installIfNotAvailable + this.androidMinimumVersion = minimumVersion + } + + fun setHandleCodeInApp(canHandleCodeInApp: Boolean): Builder = apply { this.handleCodeInApp = canHandleCodeInApp } + + fun getHandleCodeInApp(): Boolean = handleCodeInApp + + fun setLinkDomain(linkDomain: String): Builder = apply { this.linkDomain = linkDomain } + + fun getLinkDomain(): String? = linkDomain + + @Deprecated("Use setLinkDomain") + fun setDynamicLinkDomain(dynamicLinkDomain: String): Builder = apply { this.dynamicLinkDomain = dynamicLinkDomain } + + @Deprecated("Use getLinkDomain") + fun getDynamicLinkDomain(): String? = dynamicLinkDomain + + fun build(): ActionCodeSettings { + val url = requireNotNull(url) { "ActionCodeSettings url must be set" } + require(url.isNotBlank()) { "ActionCodeSettings url must not be blank" } + return ActionCodeSettings(url, iOSBundleId, androidPackageName, androidInstallApp, androidMinimumVersion, handleCodeInApp, linkDomain, dynamicLinkDomain) + } + } + + companion object { + @JvmStatic + fun newBuilder(): Builder = Builder() + } +} diff --git a/src/main/java/com/google/firebase/auth/ActionCodeUrl.kt b/src/main/java/com/google/firebase/auth/ActionCodeUrl.kt new file mode 100644 index 0000000..ec35fcd --- /dev/null +++ b/src/main/java/com/google/firebase/auth/ActionCodeUrl.kt @@ -0,0 +1,51 @@ +package com.google.firebase.auth + +import java.net.URI +import java.net.URLDecoder +import java.nio.charset.StandardCharsets + +/** The parts of an action link, mirroring the Android class; [parseLink] reads one, unwrapping a Dynamic Link. */ +class ActionCodeUrl private constructor( + val apiKey: String?, + val code: String?, + val continueUrl: String?, + val languageCode: String?, + val operation: Int +) { + companion object { + /** The action link's parts, or null when [link] is not a URL with an `oobCode` and a `mode`. */ + @JvmStatic + fun parseLink(link: String): ActionCodeUrl? { + val uri = runCatching { URI(link.trim()) }.getOrNull() ?: return null + val params = queryParameters(uri.rawQuery) + params["link"]?.let { return parseLink(it) } + params["deep_link_id"]?.let { return parseLink(it) } + val code = params["oobCode"] ?: return null + val mode = params["mode"] ?: return null + return ActionCodeUrl(params["apiKey"], code, params["continueUrl"], params["lang"], operationOf(mode)) + } + + private fun queryParameters(rawQuery: String?): Map = + rawQuery.orEmpty().split('&').filter { it.isNotEmpty() }.associate { parameter -> + val separator = parameter.indexOf('=') + if (separator < 0) { + decode(parameter) to "" + } else { + decode(parameter.substring(0, separator)) to decode(parameter.substring(separator + 1)) + } + } + + private fun decode(value: String): String = URLDecoder.decode(value, StandardCharsets.UTF_8) + + private fun operationOf(mode: String): Int = + when (mode) { + "resetPassword" -> ActionCodeResult.PASSWORD_RESET + "verifyEmail" -> ActionCodeResult.VERIFY_EMAIL + "recoverEmail" -> ActionCodeResult.RECOVER_EMAIL + "signIn" -> ActionCodeResult.SIGN_IN_WITH_EMAIL_LINK + "verifyAndChangeEmail" -> ActionCodeResult.VERIFY_BEFORE_CHANGE_EMAIL + "revertSecondFactorAddition" -> ActionCodeResult.REVERT_SECOND_FACTOR_ADDITION + else -> ActionCodeResult.ERROR + } + } +} diff --git a/src/main/java/com/google/firebase/auth/AdditionalUserInfo.java b/src/main/java/com/google/firebase/auth/AdditionalUserInfo.java new file mode 100644 index 0000000..1f038fd --- /dev/null +++ b/src/main/java/com/google/firebase/auth/AdditionalUserInfo.java @@ -0,0 +1,13 @@ +package com.google.firebase.auth; + +import java.util.Map; + +public interface AdditionalUserInfo { + Map getProfile(); + + String getProviderId(); + + String getUsername(); + + boolean isNewUser(); +} diff --git a/src/main/java/com/google/firebase/auth/AuthCredential.java b/src/main/java/com/google/firebase/auth/AuthCredential.java index bc3ac27..5dc3585 100644 --- a/src/main/java/com/google/firebase/auth/AuthCredential.java +++ b/src/main/java/com/google/firebase/auth/AuthCredential.java @@ -5,53 +5,61 @@ import java.util.ArrayList; import java.util.List; +/** + * A credential a user signs in with, mirroring the Android class: {@link #getProvider()} identifies the credential's + * provider and {@link #getSignInMethod()} the method within it. The package-private token accessors feed the Identity + * Toolkit {@code signInWithIdp} post body; a credential that is not exchanged that way (email, phone) leaves them null. + */ public abstract class AuthCredential { - private final String provider; - private final String idToken; - private final String accessToken; - private final String rawNonce; - protected AuthCredential(String provider) { - this(provider, null, null, null); + protected AuthCredential() { } - protected AuthCredential(String provider, String idToken, String accessToken, String rawNonce) { - this.provider = requireValue(provider, "provider"); - this.idToken = optionalValue(idToken, "idToken"); - this.accessToken = optionalValue(accessToken, "accessToken"); - this.rawNonce = optionalValue(rawNonce, "rawNonce"); + public abstract String getProvider(); - if (this.rawNonce != null && this.idToken == null) { - throw new IllegalArgumentException("An ID token is required when a raw nonce is supplied."); - } + public abstract String getSignInMethod(); + + /** The OAuth ID token, posted as {@code id_token}; null when the credential carries none. */ + String idToken() { + return null; } - public String getProvider() { - return provider; + /** The OAuth access token, posted as {@code access_token}; null when the credential carries none. */ + String accessToken() { + return null; } - public String getSignInMethod() { - return provider; + /** The raw nonce the ID token was requested with, posted as {@code nonce}; null when there is none. */ + String rawNonce() { + return null; + } + + /** The OAuth 1 token secret (Twitter), posted as {@code oauth_token_secret}; null when there is none. */ + String oauthTokenSecret() { + return null; } String toIdpPostBody() { List values = new ArrayList<>(); - values.add(formValue("providerId", provider)); - if (idToken != null) { - values.add(formValue("id_token", idToken)); + values.add(formValue("providerId", getProvider())); + if (idToken() != null) { + values.add(formValue("id_token", idToken())); + } + if (accessToken() != null) { + values.add(formValue("access_token", accessToken())); } - if (accessToken != null) { - values.add(formValue("access_token", accessToken)); + if (rawNonce() != null) { + values.add(formValue("nonce", rawNonce())); } - if (rawNonce != null) { - values.add(formValue("nonce", rawNonce)); + if (oauthTokenSecret() != null) { + values.add(formValue("oauth_token_secret", oauthTokenSecret())); } return String.join("&", values); } @Override public String toString() { - return getClass().getSimpleName() + "{provider='" + provider + "'}"; + return getClass().getSimpleName() + "{provider='" + getProvider() + "'}"; } static String requireValue(String value, String name) { diff --git a/src/main/java/com/google/firebase/auth/AuthResult.java b/src/main/java/com/google/firebase/auth/AuthResult.java index 1ae6213..2f37c1f 100644 --- a/src/main/java/com/google/firebase/auth/AuthResult.java +++ b/src/main/java/com/google/firebase/auth/AuthResult.java @@ -1,5 +1,9 @@ package com.google.firebase.auth; public interface AuthResult { + AdditionalUserInfo getAdditionalUserInfo(); + + AuthCredential getCredential(); + FirebaseUser getUser(); } diff --git a/src/main/java/com/google/firebase/auth/AuthResultImpl.kt b/src/main/java/com/google/firebase/auth/AuthResultImpl.kt new file mode 100644 index 0000000..7d792b5 --- /dev/null +++ b/src/main/java/com/google/firebase/auth/AuthResultImpl.kt @@ -0,0 +1,76 @@ +package com.google.firebase.auth + +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.JsonNull +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.booleanOrNull +import kotlinx.serialization.json.contentOrNull +import kotlinx.serialization.json.doubleOrNull +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive +import kotlinx.serialization.json.longOrNull + +internal data class AuthResultImpl( + private val user: FirebaseUser?, + private val additionalUserInfo: AdditionalUserInfo?, + private val credential: AuthCredential? +) : AuthResult { + override fun getUser(): FirebaseUser? = user + + override fun getAdditionalUserInfo(): AdditionalUserInfo? = additionalUserInfo + + override fun getCredential(): AuthCredential? = credential +} + +/** What a sign-in response says about the account beyond the user: provider, raw profile and whether it was created. */ +internal class AdditionalUserInfoImpl( + private val providerId: String?, + private val profile: Map, + private val username: String?, + private val newUser: Boolean +) : AdditionalUserInfo { + override fun getProviderId(): String? = providerId + + override fun getProfile(): Map = profile + + override fun getUsername(): String? = username + + override fun isNewUser(): Boolean = newUser + + companion object { + fun from(data: JsonObject, newUserByDefault: Boolean): AdditionalUserInfoImpl { + val profile = + data["rawUserInfo"]?.jsonPrimitive?.contentOrNull + ?.let { raw -> runCatching { jsonParser.parseToJsonElement(raw).jsonObject }.getOrNull() } + ?.let { json -> json.mapValues { (_, value) -> value.plainValue } } + .orEmpty() + return AdditionalUserInfoImpl( + providerId = data["providerId"]?.jsonPrimitive?.contentOrNull, + profile = profile, + username = data["screenName"]?.jsonPrimitive?.contentOrNull, + newUser = data["isNewUser"]?.jsonPrimitive?.booleanOrNull ?: newUserByDefault + ) + } + + /** The OAuth credential a `signInWithIdp` response returns alongside the user, when it does. */ + fun credentialOf(data: JsonObject): AuthCredential? { + val providerId = data["providerId"]?.jsonPrimitive?.contentOrNull ?: return null + val idToken = data["oauthIdToken"]?.jsonPrimitive?.contentOrNull + val accessToken = data["oauthAccessToken"]?.jsonPrimitive?.contentOrNull + if (idToken == null && accessToken == null) return null + return OAuthCredentialImpl(providerId, idToken, accessToken, data["oauthTokenSecret"]?.jsonPrimitive?.contentOrNull, null) + } + } +} + +/** A JSON value as the Kotlin value the Android SDK's profile map holds: null, Boolean, Long, Double, String, List or Map. */ +private val JsonElement.plainValue: Any? + get() = + when (this) { + is JsonNull -> null + is JsonArray -> map { it.plainValue } + is JsonObject -> mapValues { (_, value) -> value.plainValue } + is JsonPrimitive -> if (isString) content else booleanOrNull ?: longOrNull ?: doubleOrNull ?: content + } diff --git a/src/main/java/com/google/firebase/auth/EmailAuthCredential.java b/src/main/java/com/google/firebase/auth/EmailAuthCredential.java new file mode 100644 index 0000000..dcb7d2c --- /dev/null +++ b/src/main/java/com/google/firebase/auth/EmailAuthCredential.java @@ -0,0 +1,36 @@ +package com.google.firebase.auth; + +/** An email credential: an email with either a password or a sign-in link, as {@link EmailAuthProvider} creates them. */ +public class EmailAuthCredential extends AuthCredential { + private final String email; + private final String password; + private final String emailLink; + + EmailAuthCredential(String email, String password, String emailLink) { + this.email = requireValue(email, "email"); + this.password = password; + this.emailLink = emailLink; + } + + @Override + public String getProvider() { + return EmailAuthProvider.PROVIDER_ID; + } + + @Override + public String getSignInMethod() { + return emailLink != null ? EmailAuthProvider.EMAIL_LINK_SIGN_IN_METHOD : EmailAuthProvider.EMAIL_PASSWORD_SIGN_IN_METHOD; + } + + String getEmail() { + return email; + } + + String getPassword() { + return password; + } + + String getEmailLink() { + return emailLink; + } +} diff --git a/src/main/java/com/google/firebase/auth/EmailAuthProvider.java b/src/main/java/com/google/firebase/auth/EmailAuthProvider.java index 4e395f0..235108e 100644 --- a/src/main/java/com/google/firebase/auth/EmailAuthProvider.java +++ b/src/main/java/com/google/firebase/auth/EmailAuthProvider.java @@ -1,12 +1,24 @@ package com.google.firebase.auth; -import kotlin.NotImplementedError; - public class EmailAuthProvider { + public static final String PROVIDER_ID = "password"; + public static final String EMAIL_PASSWORD_SIGN_IN_METHOD = "password"; + public static final String EMAIL_LINK_SIGN_IN_METHOD = "emailLink"; + + private EmailAuthProvider() { + } + public static AuthCredential getCredential(String email, String password) { - throw new NotImplementedError(); + return new EmailAuthCredential(email, AuthCredential.requireValue(password, "password"), null); } + public static AuthCredential getCredentialWithLink(String email, String emailLink) { - throw new NotImplementedError(); + ActionCodeUrl url = ActionCodeUrl.parseLink(AuthCredential.requireValue(emailLink, "emailLink")); + if (url == null || url.getCode() == null) { + throw new IllegalArgumentException( + "Given link is not a valid email link. Please use FirebaseAuth#isSignInWithEmailLink(String) to determine this before calling this function" + ); + } + return new EmailAuthCredential(email, null, emailLink); } } diff --git a/src/main/java/com/google/firebase/auth/FacebookAuthCredential.java b/src/main/java/com/google/firebase/auth/FacebookAuthCredential.java new file mode 100644 index 0000000..2cf06e1 --- /dev/null +++ b/src/main/java/com/google/firebase/auth/FacebookAuthCredential.java @@ -0,0 +1,24 @@ +package com.google.firebase.auth; + +public class FacebookAuthCredential extends AuthCredential { + private final String accessToken; + + FacebookAuthCredential(String accessToken) { + this.accessToken = requireValue(accessToken, "accessToken"); + } + + @Override + public String getProvider() { + return FacebookAuthProvider.PROVIDER_ID; + } + + @Override + public String getSignInMethod() { + return FacebookAuthProvider.FACEBOOK_SIGN_IN_METHOD; + } + + @Override + String accessToken() { + return accessToken; + } +} diff --git a/src/main/java/com/google/firebase/auth/FacebookAuthProvider.java b/src/main/java/com/google/firebase/auth/FacebookAuthProvider.java index b210cda..88b7d32 100644 --- a/src/main/java/com/google/firebase/auth/FacebookAuthProvider.java +++ b/src/main/java/com/google/firebase/auth/FacebookAuthProvider.java @@ -1,9 +1,13 @@ package com.google.firebase.auth; -import kotlin.NotImplementedError; - public class FacebookAuthProvider { + public static final String PROVIDER_ID = "facebook.com"; + public static final String FACEBOOK_SIGN_IN_METHOD = "facebook.com"; + + private FacebookAuthProvider() { + } + public static AuthCredential getCredential(String accessToken) { - throw new NotImplementedError(); + return new FacebookAuthCredential(accessToken); } } diff --git a/src/main/java/com/google/firebase/auth/FederatedAuthProvider.java b/src/main/java/com/google/firebase/auth/FederatedAuthProvider.java new file mode 100644 index 0000000..5e24761 --- /dev/null +++ b/src/main/java/com/google/firebase/auth/FederatedAuthProvider.java @@ -0,0 +1,7 @@ +package com.google.firebase.auth; + +/** A provider whose sign-in runs through a browser or Activity on Android; those flows are not available on the JVM. */ +public abstract class FederatedAuthProvider { + public FederatedAuthProvider() { + } +} diff --git a/src/main/java/com/google/firebase/auth/FirebaseAuth.kt b/src/main/java/com/google/firebase/auth/FirebaseAuth.kt index 9ed862e..82f9bc0 100644 --- a/src/main/java/com/google/firebase/auth/FirebaseAuth.kt +++ b/src/main/java/com/google/firebase/auth/FirebaseAuth.kt @@ -13,6 +13,8 @@ import com.google.firebase.auth.internal.InternalAuthProvider import com.google.firebase.internal.InternalTokenResult import com.google.firebase.internal.api.FirebaseNoSignedInUserException import kotlinx.coroutines.launch +import android.app.Activity +import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable import kotlinx.serialization.Transient import kotlinx.serialization.json.Json @@ -40,6 +42,7 @@ import okhttp3.RequestBody.Companion.toRequestBody import okhttp3.Response import java.io.IOException import java.util.Base64 +import java.util.Locale import java.util.concurrent.CopyOnWriteArrayList import java.util.concurrent.TimeUnit @@ -63,7 +66,8 @@ data class FirebaseUserImpl internal constructor( val expiresIn: Int, val createdAt: Long, override val email: String?, - override val photoUrl: String?, + @SerialName("photoUrl") + val photoUrlString: String?, override val displayName: String?, override val phoneNumber: String? = null, override val isEmailVerified: Boolean = false, @@ -96,7 +100,7 @@ data class FirebaseUserImpl internal constructor( expiresIn = data["expiresIn"]?.jsonPrimitive?.intOrNull ?: data.getValue("expires_in").jsonPrimitive.int, createdAt = createdAt, email = email, - photoUrl = photoUrl ?: data["photo_url"]?.jsonPrimitive?.contentOrNull, + photoUrlString = photoUrl ?: data["photo_url"]?.jsonPrimitive?.contentOrNull, displayName = displayName ?: data["display_name"]?.jsonPrimitive?.contentOrNull, phoneNumber = phoneNumber, isEmailVerified = isEmailVerified, @@ -110,11 +114,14 @@ data class FirebaseUserImpl internal constructor( override val metadata: FirebaseUserMetadata get() = FirebaseUserMetadata(createdAt, lastSignInAt) + override val photoUrl: Uri? + get() = photoUrlString?.let(Uri::parse) + override val providerData: List - get() = providerIds.map { provider -> UserInfo(displayName, email, phoneNumber, photoUrl, provider, uid) } + get() = providerIds.map { provider -> ProviderUserInfo(displayName, email, phoneNumber, photoUrlString, provider, uid, isEmailVerified) } override val providerId: String - get() = "firebase" + get() = FirebaseAuthProvider.PROVIDER_ID val claims: Map by lazy { jsonParser @@ -182,7 +189,6 @@ data class FirebaseUserImpl internal constructor( return source.task } - // TODO implement ActionCodeSettings and pass it to the url override fun verifyBeforeUpdateEmail( newEmail: String, actionCodeSettings: ActionCodeSettings? @@ -195,7 +201,7 @@ data class FirebaseUserImpl internal constructor( "email" to JsonPrimitive(email), "newEmail" to JsonPrimitive(newEmail), "requestType" to JsonPrimitive(OobRequestType.VERIFY_AND_CHANGE_EMAIL.name) - ) + ) + actionCodeSettings?.toRequestFields().orEmpty() ).toString().toRequestBody(FirebaseAuth.getInstance(app).json) val request = Request @@ -243,6 +249,17 @@ data class FirebaseUserImpl internal constructor( override fun linkWithCredential(credential: AuthCredential): Task = FirebaseAuth.getInstance(app).linkWithCredential(this, credential) + override fun sendEmailVerification(actionCodeSettings: ActionCodeSettings?): Task = + FirebaseAuth.getInstance(app).sendOobCode( + "sendEmailVerification", + OobRequestType.VERIFY_EMAIL, + mapOf("idToken" to JsonPrimitive(idToken)), + actionCodeSettings + ) + + override fun updatePhoneNumber(credential: PhoneAuthCredential): Task = + FirebaseAuth.getInstance(app).updatePhoneNumber(this, credential) + fun updateProfile( displayName: String?, photoUrl: String? @@ -340,8 +357,15 @@ class FirebaseAuth constructor( FirebaseAuthInvalidUserException("UNKNOWN_ERROR", "accounts API returned an empty response.") ) } else { + val data = jsonParser.parseToJsonElement(responseBody).jsonObject user = setResult(responseBody) - source.setResult(AuthResult { user }) + source.setResult( + AuthResultImpl( + user, + AdditionalUserInfoImpl.from(data, newUserByDefault = url.endsWith("signUp") || url.endsWith("signupNewUser")), + AdditionalUserInfoImpl.credentialOf(data) + ) + ) } } } catch (exception: Exception) { @@ -471,10 +495,10 @@ class FirebaseAuth constructor( uid = responseUid(data, previous.idToken), createdAt = profile["createdAt"]?.jsonPrimitive?.longOrNull ?: previous.createdAt, email = profile["email"]?.jsonPrimitive?.contentOrNull ?: previous.email, - photoUrl = profile["photoUrl"]?.jsonPrimitive?.contentOrNull ?: previous.photoUrl, + photoUrlString = profile["photoUrl"]?.jsonPrimitive?.contentOrNull ?: previous.photoUrlString, displayName = profile["displayName"]?.jsonPrimitive?.contentOrNull ?: previous.displayName ) - source.setResult(AuthResult { user }) + source.setResult(AuthResultImpl(user, null, null)) } catch (exception: Exception) { source.setException(exception) } @@ -647,7 +671,7 @@ class FirebaseAuth constructor( data = this, isAnonymous = user.isAnonymous, email = user.email, - photoUrl = user.photoUrl, + photoUrl = user.photoUrlString, displayName = user.displayName, phoneNumber = user.phoneNumber, isEmailVerified = user.isEmailVerified, @@ -740,7 +764,7 @@ class FirebaseAuth constructor( expiresIn = newBody["expiresIn"]?.jsonPrimitive?.intOrNull ?: prev.expiresIn, createdAt = prev.createdAt, email = newBody["newEmail"]?.jsonPrimitive?.contentOrNull ?: prev.email, - photoUrl = newBody["photoUrl"]?.jsonPrimitive?.contentOrNull ?: prev.photoUrl, + photoUrlString = newBody["photoUrl"]?.jsonPrimitive?.contentOrNull ?: prev.photoUrlString, displayName = newBody["displayName"]?.jsonPrimitive?.contentOrNull ?: prev.displayName, phoneNumber = prev.phoneNumber, isEmailVerified = prev.isEmailVerified, @@ -818,7 +842,7 @@ class FirebaseAuth constructor( expiresIn = newBody["expiresIn"]?.jsonPrimitive?.intOrNull ?: prev.expiresIn, createdAt = prev.createdAt, email = newBody["newEmail"]?.jsonPrimitive?.contentOrNull ?: prev.email, - photoUrl = newBody["photoUrl"]?.jsonPrimitive?.contentOrNull ?: prev.photoUrl, + photoUrlString = newBody["photoUrl"]?.jsonPrimitive?.contentOrNull ?: prev.photoUrlString, displayName = newBody["displayName"]?.jsonPrimitive?.contentOrNull ?: prev.displayName, phoneNumber = prev.phoneNumber, isEmailVerified = prev.isEmailVerified, @@ -888,7 +912,101 @@ class FirebaseAuth constructor( user = user?.copy(urlFactory = urlFactory) } - fun sendPasswordResetEmail(email: String, settings: ActionCodeSettings?): Task = TODO() + fun sendPasswordResetEmail(email: String): Task = sendPasswordResetEmail(email, null) + + fun sendPasswordResetEmail(email: String, settings: ActionCodeSettings?): Task = + sendOobCode("sendPasswordResetEmail", OobRequestType.PASSWORD_RESET, mapOf("email" to JsonPrimitive(email)), settings) + + /** Posts [fields] with [type] to `accounts:sendOobCode`, the request behind every action email. */ + internal fun sendOobCode( + action: String, + type: OobRequestType, + fields: Map, + settings: ActionCodeSettings? + ): Task = + postJson( + action, + "identitytoolkit.googleapis.com/v1/accounts:sendOobCode", + JsonObject(mapOf("requestType" to JsonPrimitive(type.name)) + fields + settings?.toRequestFields().orEmpty()) + ).onSuccessTask { Tasks.forResult(Unit) } + + /** + * Posts [body] to [url] and completes with the parsed response, or with the error [createAuthInvalidUserException] + * reads from an unsuccessful one; the language code, when set, travels as the `X-Firebase-Locale` header. + */ + private fun postJson( + action: String, + url: String, + body: JsonObject + ): Task { + val source = TaskCompletionSource() + val request = + Request + .Builder() + .url(urlFactory.buildUrl(url)) + .post(body.toString().toRequestBody(json)) + .apply { languageCode?.let { header("X-Firebase-Locale", it) } } + .build() + client.newCall(request).enqueue( + object : Callback { + override fun onFailure( + call: Call, + e: IOException + ) { + source.setException(FirebaseException(e.toString(), e)) + } + + @Throws(IOException::class) + override fun onResponse( + call: Call, + response: Response + ) { + if (!response.isSuccessful) { + source.setException(createAuthInvalidUserException(action, request, response)) + } else { + try { + val responseBody = response.body?.use { it.string() }.orEmpty().ifBlank { "{}" } + source.setResult(jsonParser.parseToJsonElement(responseBody).jsonObject) + } catch (exception: Exception) { + source.setException(exception) + } + } + } + } + ) + return source.task + } + + private fun enqueueEmailAuthPost( + credential: EmailAuthCredential, + currentIdToken: String?, + setResult: (responseBody: String) -> FirebaseUserImpl + ): Task { + val link = credential.emailLink + val values = linkedMapOf("email" to JsonPrimitive(credential.email)) + val url = + if (link != null) { + val code = ActionCodeUrl.parseLink(link)?.code + ?: return Tasks.forException(IllegalArgumentException("The email link carries no action code")) + values["oobCode"] = JsonPrimitive(code) + "identitytoolkit.googleapis.com/v1/accounts:signInWithEmailLink" + } else { + values["password"] = JsonPrimitive(credential.password) + values["returnSecureToken"] = JsonPrimitive(true) + // Linking a password sets it on the signed-in account; signing in verifies it. + if (currentIdToken != null) "identitytoolkit.googleapis.com/v1/accounts:update" else "www.googleapis.com/identitytoolkit/v3/relyingparty/verifyPassword" + } + if (currentIdToken != null) { + values["idToken"] = JsonPrimitive(currentIdToken) + } + return enqueueAuthPost(url, JsonObject(values).toString().toRequestBody(json), setResult).task + } + + /** Links the phone number [credential] verifies to [currentUser], as the Android `updatePhoneNumber` does. */ + internal fun updatePhoneNumber( + currentUser: FirebaseUserImpl, + credential: PhoneAuthCredential + ): Task = linkWithCredential(currentUser, credential).onSuccessTask { Tasks.forResult(Unit) } fun signInWithCredential(authCredential: AuthCredential): Task = enqueueCredentialAuthPost(authCredential, currentIdToken = null) { responseBody -> FirebaseUserImpl( @@ -920,7 +1038,7 @@ class FirebaseAuth constructor( data = data, isAnonymous = false, email = data["email"]?.jsonPrimitive?.contentOrNull ?: signedInUser.email, - photoUrl = data["photoUrl"]?.jsonPrimitive?.contentOrNull ?: signedInUser.photoUrl, + photoUrl = data["photoUrl"]?.jsonPrimitive?.contentOrNull ?: signedInUser.photoUrlString, displayName = data["displayName"]?.jsonPrimitive?.contentOrNull ?: signedInUser.displayName, phoneNumber = data["phoneNumber"]?.jsonPrimitive?.contentOrNull ?: signedInUser.phoneNumber, isEmailVerified = data["emailVerified"]?.jsonPrimitive?.booleanOrNull ?: signedInUser.isEmailVerified, @@ -944,10 +1062,10 @@ class FirebaseAuth constructor( currentIdToken: String?, setResult: (responseBody: String) -> FirebaseUserImpl ): Task = - if (authCredential is PhoneAuthCredential) { - enqueuePhoneAuthPost(authCredential, currentIdToken, setResult) - } else { - enqueueIdpAuthPost(authCredential, currentIdToken, setResult) + when (authCredential) { + is PhoneAuthCredential -> enqueuePhoneAuthPost(authCredential, currentIdToken, setResult) + is EmailAuthCredential -> enqueueEmailAuthPost(authCredential, currentIdToken, setResult) + else -> enqueueIdpAuthPost(authCredential, currentIdToken, setResult) } private fun enqueueIdpAuthPost( @@ -991,34 +1109,111 @@ class FirebaseAuth constructor( setResult = setResult ).task } - fun checkActionCode(code: String): Task = TODO() + /** What an action code is for and which account it concerns, from `accounts:resetPassword` called with the code alone. */ + fun checkActionCode(code: String): Task = + postJson("checkActionCode", "identitytoolkit.googleapis.com/v1/accounts:resetPassword", JsonObject(mapOf("oobCode" to JsonPrimitive(code)))) + .onSuccessTask { data -> Tasks.forResult(ActionCodeResultImpl(requireNotNull(data))) } fun confirmPasswordReset( code: String, newPassword: String - ): Task = TODO() - - fun fetchSignInMethodsForEmail(email: String): Task = TODO() + ): Task = + postJson( + "confirmPasswordReset", + "identitytoolkit.googleapis.com/v1/accounts:resetPassword", + JsonObject(mapOf("oobCode" to JsonPrimitive(code), "newPassword" to JsonPrimitive(newPassword))) + ).onSuccessTask { Tasks.forResult(Unit) } + + /** The email a password reset code was issued for, which also checks that the code is valid. */ + fun verifyPasswordResetCode(code: String): Task = + postJson("verifyPasswordResetCode", "identitytoolkit.googleapis.com/v1/accounts:resetPassword", JsonObject(mapOf("oobCode" to JsonPrimitive(code)))) + .onSuccessTask { data -> Tasks.forResult(requireNotNull(data)["email"]?.jsonPrimitive?.contentOrNull ?: throw FirebaseAuthActionCodeException("ERROR_INVALID_ACTION_CODE", "The action code has no email")) } + + /** Applies a verification, email recovery or second-factor reversal code. */ + fun applyActionCode(code: String): Task = + postJson("applyActionCode", "identitytoolkit.googleapis.com/v1/accounts:update", JsonObject(mapOf("oobCode" to JsonPrimitive(code)))) + .onSuccessTask { Tasks.forResult(Unit) } + + @Deprecated("Email enumeration protection hides the sign-in methods of other accounts; Firebase recommends against this call") + fun fetchSignInMethodsForEmail(email: String): Task = + postJson( + "fetchSignInMethodsForEmail", + "identitytoolkit.googleapis.com/v1/accounts:createAuthUri", + JsonObject(mapOf("identifier" to JsonPrimitive(email), "continueUri" to JsonPrimitive("http://localhost"))) + ).onSuccessTask { data -> + val methods = requireNotNull(data)["signinMethods"]?.jsonArray?.mapNotNull { it.jsonPrimitive.contentOrNull }.orEmpty() + Tasks.forResult(SignInMethodQueryResultImpl(methods)) + } + /** Emails [email] a sign-in link leading to [actionCodeSettings]' URL, which must be handled in the app. */ fun sendSignInLinkToEmail( email: String, actionCodeSettings: ActionCodeSettings - ): Task = TODO() + ): Task { + if (!actionCodeSettings.canHandleCodeInApp()) { + return Tasks.forException(IllegalArgumentException("You must set canHandleCodeInApp in your ActionCodeSettings to true for Email-Link Sign-in.")) + } + return sendOobCode("sendSignInLinkToEmail", OobRequestType.EMAIL_SIGNIN, mapOf("email" to JsonPrimitive(email)), actionCodeSettings) + } - fun verifyPasswordResetCode(code: String): Task = TODO() + fun isSignInWithEmailLink(link: String): Boolean = ActionCodeUrl.parseLink(link)?.operation == ActionCodeResult.SIGN_IN_WITH_EMAIL_LINK - fun updateCurrentUser(user: FirebaseUser): Task = TODO() + fun signInWithEmailLink( + email: String, + link: String + ): Task = + signInWithCredential(EmailAuthProvider.getCredentialWithLink(email, link)) + + /** Makes [user], obtained from this port's own sign-in, the current user. */ + fun updateCurrentUser(user: FirebaseUser): Task { + val restored = user as? FirebaseUserImpl + ?: return Tasks.forException(IllegalArgumentException("The user must come from a firebase-java-sdk sign-in")) + this.user = restored.copy(app = app, urlFactory = urlFactory) + return Tasks.forResult(Unit) + } - fun applyActionCode(code: String): Task = TODO() + /** The language of the emails this instance sends, as the `X-Firebase-Locale` header; null for the project default. */ + var languageCode: String? = null - val languageCode: String get() = TODO() + /** Sets [languageCode] to the JVM's default locale. */ + fun useAppLanguage() { + languageCode = Locale.getDefault().toLanguageTag() + } - fun isSignInWithEmailLink(link: String): Boolean = TODO() + /** The tenant to sign in to; the JVM port always uses the project's default tenant. */ + var tenantId: String? = null - fun signInWithEmailLink( - email: String, - link: String - ): Task = TODO() + /** The domain hosting the project's sign-in helpers; the JVM port runs no browser flows, so it is only kept. */ + var customAuthDomain: String? = null + + val firebaseAuthSettings: FirebaseAuthSettings = FirebaseAuthSettingsImpl() + + /** The result of a provider sign-in started through an Activity; there is never one on the JVM. */ + val pendingAuthResult: Task? get() = null + + /** reCAPTCHA Enterprise protects phone and email flows on Android; the JVM port has nothing to initialise. */ + fun initializeRecaptchaConfig(): Task = Tasks.forResult(null) + + /** Revokes an Apple sign-in [token] for the current user, as the Android SDK does before an account deletion. */ + fun revokeAccessToken(token: String): Task { + val idToken = user?.idToken + ?: return Tasks.forException(FirebaseNoSignedInUserException("Please sign in before trying to revoke an access token.")) + return postJson( + "revokeAccessToken", + "identitytoolkit.googleapis.com/v2/accounts:revokeToken", + JsonObject( + mapOf( + "providerId" to JsonPrimitive("apple.com"), + "tokenType" to JsonPrimitive("ACCESS_TOKEN"), + "token" to JsonPrimitive(token), + "idToken" to JsonPrimitive(idToken) + ) + ) + ).onSuccessTask { Tasks.forResult(null) } + } - fun setLanguageCode(value: String): Nothing = TODO() + fun startActivityForSignInWithProvider( + activity: Activity, + federatedAuthProvider: FederatedAuthProvider + ): Task = unsupportedTask(ACTIVITY_FLOWS_UNSUPPORTED) } diff --git a/src/main/java/com/google/firebase/auth/FirebaseAuthMissingActivityForRecaptchaException.kt b/src/main/java/com/google/firebase/auth/FirebaseAuthMissingActivityForRecaptchaException.kt new file mode 100644 index 0000000..d15fa5c --- /dev/null +++ b/src/main/java/com/google/firebase/auth/FirebaseAuthMissingActivityForRecaptchaException.kt @@ -0,0 +1,5 @@ +package com.google.firebase.auth + +/** Raised on Android when a reCAPTCHA flow has no Activity to run in; the JVM port never runs one. */ +class FirebaseAuthMissingActivityForRecaptchaException : + FirebaseAuthException("ERROR_MISSING_ACTIVITY", "An Activity is required to start the reCAPTCHA flow, which is not available on the JVM.") diff --git a/src/main/java/com/google/firebase/auth/FirebaseAuthMultiFactorException.kt b/src/main/java/com/google/firebase/auth/FirebaseAuthMultiFactorException.kt new file mode 100644 index 0000000..8188070 --- /dev/null +++ b/src/main/java/com/google/firebase/auth/FirebaseAuthMultiFactorException.kt @@ -0,0 +1,9 @@ +package com.google.firebase.auth + +class FirebaseAuthMultiFactorException( + errorCode: String, + detailMessage: String, + private val resolver: MultiFactorResolver +) : FirebaseAuthException(errorCode, detailMessage) { + fun getResolver(): MultiFactorResolver = resolver +} diff --git a/src/main/java/com/google/firebase/auth/FirebaseAuthProvider.java b/src/main/java/com/google/firebase/auth/FirebaseAuthProvider.java new file mode 100644 index 0000000..ed5544f --- /dev/null +++ b/src/main/java/com/google/firebase/auth/FirebaseAuthProvider.java @@ -0,0 +1,5 @@ +package com.google.firebase.auth; + +public interface FirebaseAuthProvider { + String PROVIDER_ID = "firebase"; +} diff --git a/src/main/java/com/google/firebase/auth/FirebaseAuthSettings.java b/src/main/java/com/google/firebase/auth/FirebaseAuthSettings.java new file mode 100644 index 0000000..96a5316 --- /dev/null +++ b/src/main/java/com/google/firebase/auth/FirebaseAuthSettings.java @@ -0,0 +1,13 @@ +package com.google.firebase.auth; + +/** Test settings of a {@link FirebaseAuth} instance; they concern phone verification, which the JVM port does not perform. */ +public abstract class FirebaseAuthSettings { + public FirebaseAuthSettings() { + } + + public abstract void forceRecaptchaFlowForTesting(boolean forceRecaptchaFlow); + + public abstract void setAppVerificationDisabledForTesting(boolean disabled); + + public abstract void setAutoRetrievedSmsCodeForPhoneNumber(String phoneNumber, String smsCode); +} diff --git a/src/main/java/com/google/firebase/auth/FirebaseAuthUserCollisionException.kt b/src/main/java/com/google/firebase/auth/FirebaseAuthUserCollisionException.kt index 6cc4959..6b299b9 100644 --- a/src/main/java/com/google/firebase/auth/FirebaseAuthUserCollisionException.kt +++ b/src/main/java/com/google/firebase/auth/FirebaseAuthUserCollisionException.kt @@ -1,3 +1,17 @@ package com.google.firebase.auth -class FirebaseAuthUserCollisionException(errorCode: String, detailMessage: String) : FirebaseAuthException(errorCode, detailMessage) +class FirebaseAuthUserCollisionException(errorCode: String, detailMessage: String) : FirebaseAuthException(errorCode, detailMessage) { + private var email: String? = null + private var updatedCredential: AuthCredential? = null + + /** The email of the account that already exists, when the server reported it. */ + fun getEmail(): String? = email + + /** The credential the sign-in produced for the existing account, when the server returned one. */ + fun getUpdatedCredential(): AuthCredential? = updatedCredential + + internal fun withDetails(email: String?, updatedCredential: AuthCredential?): FirebaseAuthUserCollisionException = apply { + this.email = email + this.updatedCredential = updatedCredential + } +} diff --git a/src/main/java/com/google/firebase/auth/FirebaseAuthWeakPasswordException.kt b/src/main/java/com/google/firebase/auth/FirebaseAuthWeakPasswordException.kt index cacc7a7..04751a5 100644 --- a/src/main/java/com/google/firebase/auth/FirebaseAuthWeakPasswordException.kt +++ b/src/main/java/com/google/firebase/auth/FirebaseAuthWeakPasswordException.kt @@ -1,3 +1,12 @@ package com.google.firebase.auth -class FirebaseAuthWeakPasswordException(errorCode: String, detailMessage: String) : FirebaseAuthInvalidCredentialsException(errorCode, detailMessage) +class FirebaseAuthWeakPasswordException( + errorCode: String, + detailMessage: String, + private val reason: String? +) : FirebaseAuthInvalidCredentialsException(errorCode, detailMessage) { + constructor(errorCode: String, detailMessage: String) : this(errorCode, detailMessage, null) + + /** Why the password was rejected, when the server said. */ + fun getReason(): String? = reason +} diff --git a/src/main/java/com/google/firebase/auth/FirebaseUser.kt b/src/main/java/com/google/firebase/auth/FirebaseUser.kt index 2e8b49c..2413b2b 100644 --- a/src/main/java/com/google/firebase/auth/FirebaseUser.kt +++ b/src/main/java/com/google/firebase/auth/FirebaseUser.kt @@ -1,49 +1,61 @@ package com.google.firebase.auth +import android.app.Activity +import android.net.Uri import com.google.android.gms.tasks.Task -abstract class FirebaseUser { - abstract val uid: String - abstract val email: String? - abstract val photoUrl: String? - abstract val displayName: String? +abstract class FirebaseUser : UserInfo { + abstract override val uid: String + abstract override val email: String? + abstract override val photoUrl: Uri? + abstract override val displayName: String? + abstract override val phoneNumber: String? + abstract override val isEmailVerified: Boolean + abstract override val providerId: String abstract val isAnonymous: Boolean + abstract val metadata: FirebaseUserMetadata + abstract val providerData: List + + /** The tenant the user belongs to; the JVM port signs in to the project's default tenant. */ + open val tenantId: String? get() = null + + val multiFactor: MultiFactor get() = UnsupportedMultiFactor() abstract fun delete(): Task abstract fun reload(): Task - abstract fun verifyBeforeUpdateEmail( - newEmail: String, - actionCodeSettings: ActionCodeSettings? - ): Task + abstract fun getIdToken(forceRefresh: Boolean): Task abstract fun updateEmail(email: String): Task - abstract fun getIdToken(forceRefresh: Boolean): Task - abstract fun updateProfile(request: UserProfileChangeRequest): Task - abstract val phoneNumber: String? - abstract val isEmailVerified: Boolean - abstract val metadata: FirebaseUserMetadata - val multiFactor: MultiFactor get() = TODO() - abstract val providerData: List - abstract val providerId: String - abstract fun linkWithCredential(credential: AuthCredential): Task - fun sendEmailVerification(): Task = TODO() + fun verifyBeforeUpdateEmail(newEmail: String): Task = verifyBeforeUpdateEmail(newEmail, null) + + abstract fun verifyBeforeUpdateEmail(newEmail: String, actionCodeSettings: ActionCodeSettings?): Task + + fun sendEmailVerification(): Task = sendEmailVerification(null) + + abstract fun sendEmailVerification(actionCodeSettings: ActionCodeSettings?): Task - fun sendEmailVerification(actionCodeSettings: ActionCodeSettings): Task = TODO() + abstract fun updatePhoneNumber(credential: PhoneAuthCredential): Task + + fun startActivityForLinkWithProvider(activity: Activity, federatedAuthProvider: FederatedAuthProvider): Task = + unsupportedTask(ACTIVITY_FLOWS_UNSUPPORTED) + + fun startActivityForReauthenticateWithProvider(activity: Activity, federatedAuthProvider: FederatedAuthProvider): Task = + unsupportedTask(ACTIVITY_FLOWS_UNSUPPORTED) fun unlink(provider: String): Task = TODO() fun updatePassword(password: String): Task = TODO() - fun updatePhoneNumber(credential: AuthCredential): Task = TODO() - fun reauthenticate(credential: AuthCredential): Task = TODO() fun reauthenticateAndRetrieveData(credential: AuthCredential): Task = TODO() } + +internal const val ACTIVITY_FLOWS_UNSUPPORTED = "Provider sign-in through an Activity is not available on the JVM; sign in with a credential instead" diff --git a/src/main/java/com/google/firebase/auth/GithubAuthCredential.java b/src/main/java/com/google/firebase/auth/GithubAuthCredential.java new file mode 100644 index 0000000..45d4e7b --- /dev/null +++ b/src/main/java/com/google/firebase/auth/GithubAuthCredential.java @@ -0,0 +1,24 @@ +package com.google.firebase.auth; + +public class GithubAuthCredential extends AuthCredential { + private final String token; + + GithubAuthCredential(String token) { + this.token = requireValue(token, "token"); + } + + @Override + public String getProvider() { + return GithubAuthProvider.PROVIDER_ID; + } + + @Override + public String getSignInMethod() { + return GithubAuthProvider.GITHUB_SIGN_IN_METHOD; + } + + @Override + String accessToken() { + return token; + } +} diff --git a/src/main/java/com/google/firebase/auth/GithubAuthProvider.java b/src/main/java/com/google/firebase/auth/GithubAuthProvider.java index d0d429d..75dd4f7 100644 --- a/src/main/java/com/google/firebase/auth/GithubAuthProvider.java +++ b/src/main/java/com/google/firebase/auth/GithubAuthProvider.java @@ -1,9 +1,13 @@ package com.google.firebase.auth; -import kotlin.NotImplementedError; - public class GithubAuthProvider { + public static final String PROVIDER_ID = "github.com"; + public static final String GITHUB_SIGN_IN_METHOD = "github.com"; + + private GithubAuthProvider() { + } + public static AuthCredential getCredential(String token) { - throw new NotImplementedError(); + return new GithubAuthCredential(token); } } diff --git a/src/main/java/com/google/firebase/auth/GoogleAuthCredential.java b/src/main/java/com/google/firebase/auth/GoogleAuthCredential.java index 63b41b8..2db970a 100644 --- a/src/main/java/com/google/firebase/auth/GoogleAuthCredential.java +++ b/src/main/java/com/google/firebase/auth/GoogleAuthCredential.java @@ -1,8 +1,32 @@ package com.google.firebase.auth; -public final class GoogleAuthCredential extends AuthCredential { +public class GoogleAuthCredential extends AuthCredential { + private final String idToken; + private final String accessToken; + GoogleAuthCredential(String idToken, String accessToken) { - super(GoogleAuthProvider.PROVIDER_ID, idToken, accessToken, null); - requireOAuthToken(idToken, accessToken); + this.idToken = optionalValue(idToken, "idToken"); + this.accessToken = optionalValue(accessToken, "accessToken"); + requireOAuthToken(this.idToken, this.accessToken); + } + + @Override + public String getProvider() { + return GoogleAuthProvider.PROVIDER_ID; + } + + @Override + public String getSignInMethod() { + return GoogleAuthProvider.GOOGLE_SIGN_IN_METHOD; + } + + @Override + String idToken() { + return idToken; + } + + @Override + String accessToken() { + return accessToken; } } diff --git a/src/main/java/com/google/firebase/auth/MultiFactor.kt b/src/main/java/com/google/firebase/auth/MultiFactor.kt new file mode 100644 index 0000000..34b22b7 --- /dev/null +++ b/src/main/java/com/google/firebase/auth/MultiFactor.kt @@ -0,0 +1,135 @@ +package com.google.firebase.auth + +import android.app.Activity +import com.google.android.gms.tasks.Task +import com.google.android.gms.tasks.Tasks + +/* + * Multi-factor authentication, mirroring the Android classes' shapes. The JVM port cannot enrol or verify a second + * factor (phone verification and TOTP enrolment need the device flows), so the operations fail with + * UnsupportedOperationException while the types let code written against the Android SDK compile. + */ + +internal const val MULTI_FACTOR_UNSUPPORTED = "Multi-factor authentication is not supported by firebase-java-sdk" + +internal fun unsupportedTask(message: String): Task = Tasks.forException(UnsupportedOperationException(message)) + +abstract class MultiFactorInfo { + abstract val displayName: String? + abstract val enrollmentTimestamp: Long + abstract val factorId: String + abstract val uid: String + + companion object { + const val FACTOR_ID_KEY = "factorIdKey" + } +} + +class PhoneMultiFactorInfo( + override val uid: String, + override val displayName: String?, + override val enrollmentTimestamp: Long, + val phoneNumber: String +) : MultiFactorInfo() { + override val factorId: String get() = PhoneMultiFactorGenerator.FACTOR_ID +} + +class TotpMultiFactorInfo internal constructor( + override val uid: String, + override val displayName: String?, + override val enrollmentTimestamp: Long +) : MultiFactorInfo() { + override val factorId: String get() = TotpMultiFactorGenerator.FACTOR_ID +} + +abstract class MultiFactorAssertion { + abstract val factorId: String +} + +class PhoneMultiFactorAssertion(internal val credential: PhoneAuthCredential) : MultiFactorAssertion() { + override val factorId: String get() = PhoneMultiFactorGenerator.FACTOR_ID +} + +class TotpMultiFactorAssertion( + internal val enrollmentId: String?, + internal val secret: TotpSecret?, + internal val oneTimePassword: String? +) : MultiFactorAssertion() { + override val factorId: String get() = TotpMultiFactorGenerator.FACTOR_ID +} + +class PhoneMultiFactorGenerator { + companion object { + const val FACTOR_ID = "phone" + + @JvmStatic + fun getAssertion(credential: PhoneAuthCredential): PhoneMultiFactorAssertion = PhoneMultiFactorAssertion(credential) + } +} + +class TotpMultiFactorGenerator private constructor() { + companion object { + const val FACTOR_ID = "totp" + + @JvmStatic + fun generateSecret(session: MultiFactorSession): Task = unsupportedTask(MULTI_FACTOR_UNSUPPORTED) + + @JvmStatic + fun getAssertionForEnrollment(secret: TotpSecret, oneTimePassword: String): TotpMultiFactorAssertion = + TotpMultiFactorAssertion(null, secret, oneTimePassword) + + @JvmStatic + fun getAssertionForSignIn(enrollmentId: String, oneTimePassword: String): TotpMultiFactorAssertion = + TotpMultiFactorAssertion(enrollmentId, null, oneTimePassword) + } +} + +interface TotpSecret { + val codeIntervalSeconds: Int + val codeLength: Int + val enrollmentCompletionDeadline: Long + val hashAlgorithm: String + val sessionInfo: String + val sharedSecretKey: String + + fun generateQrCodeUrl(): String + + fun generateQrCodeUrl(accountName: String, issuer: String): String + + fun openInOtpApp(qrCodeUrl: String) + + fun openInOtpApp(qrCodeUrl: String, fallbackUrl: String, activity: Activity) +} + +class MultiFactorSession + +abstract class MultiFactor { + abstract val enrolledFactors: List + abstract val session: Task + + abstract fun enroll(multiFactorAssertion: MultiFactorAssertion, displayName: String?): Task + + abstract fun unenroll(multiFactorInfo: MultiFactorInfo): Task + + abstract fun unenroll(factorUid: String): Task +} + +/** The account's second factors; the JVM port enrols none. */ +internal class UnsupportedMultiFactor : MultiFactor() { + override val enrolledFactors: List get() = emptyList() + override val session: Task get() = unsupportedTask(MULTI_FACTOR_UNSUPPORTED) + + override fun enroll(multiFactorAssertion: MultiFactorAssertion, displayName: String?): Task = unsupportedTask(MULTI_FACTOR_UNSUPPORTED) + + override fun unenroll(multiFactorInfo: MultiFactorInfo): Task = unsupportedTask(MULTI_FACTOR_UNSUPPORTED) + + override fun unenroll(factorUid: String): Task = unsupportedTask(MULTI_FACTOR_UNSUPPORTED) +} + +abstract class MultiFactorResolver { + abstract val firebaseAuth: FirebaseAuth + abstract val hints: List + abstract val session: MultiFactorSession + + abstract fun resolveSignIn(assertion: MultiFactorAssertion): Task +} diff --git a/src/main/java/com/google/firebase/auth/OAuthCredential.java b/src/main/java/com/google/firebase/auth/OAuthCredential.java index 5255192..d1d4851 100644 --- a/src/main/java/com/google/firebase/auth/OAuthCredential.java +++ b/src/main/java/com/google/firebase/auth/OAuthCredential.java @@ -1,8 +1,29 @@ package com.google.firebase.auth; -public final class OAuthCredential extends AuthCredential { - OAuthCredential(String provider, String idToken, String accessToken, String rawNonce) { - super(provider, idToken, accessToken, rawNonce); - requireOAuthToken(idToken, accessToken); +/** A generic OAuth credential, mirroring the Android class; {@link OAuthProvider} creates the instances. */ +public abstract class OAuthCredential extends AuthCredential { + + public OAuthCredential() { + } + + public abstract String getAccessToken(); + + public abstract String getIdToken(); + + public abstract String getSecret(); + + @Override + String idToken() { + return getIdToken(); + } + + @Override + String accessToken() { + return getAccessToken(); + } + + @Override + String oauthTokenSecret() { + return getSecret(); } } diff --git a/src/main/java/com/google/firebase/auth/OAuthCredentialImpl.java b/src/main/java/com/google/firebase/auth/OAuthCredentialImpl.java new file mode 100644 index 0000000..da203a8 --- /dev/null +++ b/src/main/java/com/google/firebase/auth/OAuthCredentialImpl.java @@ -0,0 +1,51 @@ +package com.google.firebase.auth; + +final class OAuthCredentialImpl extends OAuthCredential { + private final String provider; + private final String idToken; + private final String accessToken; + private final String secret; + private final String rawNonce; + + OAuthCredentialImpl(String provider, String idToken, String accessToken, String secret, String rawNonce) { + this.provider = requireValue(provider, "provider"); + this.idToken = optionalValue(idToken, "idToken"); + this.accessToken = optionalValue(accessToken, "accessToken"); + this.secret = optionalValue(secret, "secret"); + this.rawNonce = optionalValue(rawNonce, "rawNonce"); + requireOAuthToken(this.idToken, this.accessToken); + if (this.rawNonce != null && this.idToken == null) { + throw new IllegalArgumentException("An ID token is required when a raw nonce is supplied."); + } + } + + @Override + public String getProvider() { + return provider; + } + + @Override + public String getSignInMethod() { + return provider; + } + + @Override + public String getAccessToken() { + return accessToken; + } + + @Override + public String getIdToken() { + return idToken; + } + + @Override + public String getSecret() { + return secret; + } + + @Override + String rawNonce() { + return rawNonce; + } +} diff --git a/src/main/java/com/google/firebase/auth/OAuthProvider.java b/src/main/java/com/google/firebase/auth/OAuthProvider.java index b7ac9aa..e5e0414 100644 --- a/src/main/java/com/google/firebase/auth/OAuthProvider.java +++ b/src/main/java/com/google/firebase/auth/OAuthProvider.java @@ -6,7 +6,7 @@ import java.util.List; import java.util.Map; -public final class OAuthProvider { +public final class OAuthProvider extends FederatedAuthProvider { private final String provider; private final FirebaseAuth auth; private final List scopes; @@ -19,8 +19,10 @@ public OAuthProvider(Builder builder) { customParameters = Collections.unmodifiableMap(new LinkedHashMap<>(builder.customParameters)); } + /** @deprecated use {@link #newCredentialBuilder(String)}. */ + @Deprecated public static AuthCredential getCredential(String providerId, String idToken, String accessToken) { - return new OAuthCredential(providerId, idToken, accessToken, null); + return new OAuthCredentialImpl(providerId, idToken, accessToken, null, null); } public String getProviderId() { @@ -61,6 +63,18 @@ public Builder setScopes(List scopes) { return this; } + public List getScopes() { + return Collections.unmodifiableList(new ArrayList<>(scopes)); + } + + public Builder addCustomParameter(String paramKey, String paramValue) { + if (paramKey == null || paramValue == null) { + throw new IllegalArgumentException("customParameter key and value must not be null."); + } + this.customParameters.put(paramKey, paramValue); + return this; + } + public Builder addCustomParameters(Map customParameters) { if (customParameters == null) { throw new IllegalArgumentException("customParameters must not be null."); @@ -101,8 +115,16 @@ public CredentialBuilder setIdTokenWithRawNonce(String idToken, String rawNonce) return this; } + public String getAccessToken() { + return accessToken; + } + + public String getIdToken() { + return idToken; + } + public AuthCredential build() { - return new OAuthCredential(provider, idToken, accessToken, rawNonce); + return new OAuthCredentialImpl(provider, idToken, accessToken, null, rawNonce); } } diff --git a/src/main/java/com/google/firebase/auth/PhoneAuthCredential.kt b/src/main/java/com/google/firebase/auth/PhoneAuthCredential.kt new file mode 100644 index 0000000..d6204d6 --- /dev/null +++ b/src/main/java/com/google/firebase/auth/PhoneAuthCredential.kt @@ -0,0 +1,18 @@ +package com.google.firebase.auth + +/** A phone credential: the verification id of a sent SMS and the code it carried, exchanged with `signInWithPhoneNumber`. */ +class PhoneAuthCredential internal constructor( + internal val verificationId: String, + val smsCode: String +) : AuthCredential(), Cloneable { + init { + require(verificationId.isNotBlank()) { "verificationId must not be blank" } + require(smsCode.isNotBlank()) { "smsCode must not be blank" } + } + + override fun getProvider(): String = PhoneAuthProvider.PROVIDER_ID + + override fun getSignInMethod(): String = PhoneAuthProvider.PHONE_SIGN_IN_METHOD + + override fun toString(): String = "PhoneAuthCredential{provider='phone'}" +} diff --git a/src/main/java/com/google/firebase/auth/PhoneAuthOptions.kt b/src/main/java/com/google/firebase/auth/PhoneAuthOptions.kt new file mode 100644 index 0000000..c5e2315 --- /dev/null +++ b/src/main/java/com/google/firebase/auth/PhoneAuthOptions.kt @@ -0,0 +1,63 @@ +package com.google.firebase.auth + +import android.app.Activity +import java.util.concurrent.TimeUnit + +/** The options of a phone number verification, mirroring the Android class; see [PhoneAuthProvider.verifyPhoneNumber]. */ +class PhoneAuthOptions private constructor( + internal val auth: FirebaseAuth, + internal val phoneNumber: String?, + internal val timeout: Long?, + internal val timeUnit: TimeUnit?, + internal val activity: Activity?, + internal val callbacks: PhoneAuthProvider.OnVerificationStateChangedCallbacks?, + internal val forceResendingToken: PhoneAuthProvider.ForceResendingToken?, + internal val multiFactorSession: MultiFactorSession?, + internal val multiFactorHint: PhoneMultiFactorInfo?, + internal val requireSmsValidation: Boolean +) { + class Builder(private val auth: FirebaseAuth) { + private var phoneNumber: String? = null + private var timeout: Long? = 60L + private var timeUnit: TimeUnit? = TimeUnit.SECONDS + private var activity: Activity? = null + private var callbacks: PhoneAuthProvider.OnVerificationStateChangedCallbacks? = null + private var forceResendingToken: PhoneAuthProvider.ForceResendingToken? = null + private var multiFactorSession: MultiFactorSession? = null + private var multiFactorHint: PhoneMultiFactorInfo? = null + private var requireSmsValidation: Boolean = false + + fun setPhoneNumber(phoneNumber: String): Builder = apply { this.phoneNumber = phoneNumber } + + fun setTimeout(timeout: Long?, unit: TimeUnit): Builder = apply { + this.timeout = timeout + this.timeUnit = unit + } + + fun setActivity(activity: Activity): Builder = apply { this.activity = activity } + + fun setCallbacks(callbacks: PhoneAuthProvider.OnVerificationStateChangedCallbacks): Builder = apply { this.callbacks = callbacks } + + fun setForceResendingToken(token: PhoneAuthProvider.ForceResendingToken): Builder = apply { this.forceResendingToken = token } + + fun setMultiFactorSession(session: MultiFactorSession): Builder = apply { this.multiFactorSession = session } + + fun setMultiFactorHint(hint: PhoneMultiFactorInfo): Builder = apply { this.multiFactorHint = hint } + + fun requireSmsValidation(require: Boolean): Builder = apply { this.requireSmsValidation = require } + + fun build(): PhoneAuthOptions { + requireNotNull(callbacks) { "You must specify callbacks via setCallbacks()." } + require(phoneNumber != null || multiFactorHint != null) { "You must specify a phone number via setPhoneNumber() or a multi-factor hint via setMultiFactorHint()." } + return PhoneAuthOptions(auth, phoneNumber, timeout, timeUnit, activity, callbacks, forceResendingToken, multiFactorSession, multiFactorHint, requireSmsValidation) + } + } + + companion object { + @JvmStatic + fun newBuilder(): Builder = Builder(FirebaseAuth.getInstance()) + + @JvmStatic + fun newBuilder(auth: FirebaseAuth): Builder = Builder(auth) + } +} diff --git a/src/main/java/com/google/firebase/auth/PhoneAuthProvider.java b/src/main/java/com/google/firebase/auth/PhoneAuthProvider.java deleted file mode 100644 index 79132b7..0000000 --- a/src/main/java/com/google/firebase/auth/PhoneAuthProvider.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.google.firebase.auth; - -import android.app.Activity; -import com.google.firebase.FirebaseException; -import kotlin.NotImplementedError; - -import java.util.concurrent.TimeUnit; - -public class PhoneAuthProvider { - public static PhoneAuthCredential getCredential(String verificationId, String smsCode) { - return new PhoneAuthCredential(verificationId, smsCode); - } - public static PhoneAuthProvider getInstance(FirebaseAuth auth) { - if (auth == null) { - throw new IllegalArgumentException("auth must not be null."); - } - return new PhoneAuthProvider(); - } - - public void verifyPhoneNumber(String phoneNumber, long timeout, TimeUnit unit, Activity activity, PhoneAuthProvider.OnVerificationStateChangedCallbacks callbacks) { - throw new NotImplementedError(); - } - - public void verifyPhoneNumber(String phoneNumber, long timeout, TimeUnit unit, Activity activity, PhoneAuthProvider.OnVerificationStateChangedCallbacks callbacks, ForceResendingToken forceResending) { - throw new NotImplementedError(); - } - - public static abstract class OnVerificationStateChangedCallbacks { - public void onCodeAutoRetrievalTimeOut(String verificationId) { - throw new NotImplementedError(); - } - public void onCodeSent(String verificationId, PhoneAuthProvider.ForceResendingToken forceResendingToken) { - throw new NotImplementedError(); - } - public abstract void onVerificationCompleted(PhoneAuthCredential credential); - public abstract void onVerificationFailed(FirebaseException exception); - } - - public static class ForceResendingToken { - - } -} diff --git a/src/main/java/com/google/firebase/auth/PhoneAuthProvider.kt b/src/main/java/com/google/firebase/auth/PhoneAuthProvider.kt new file mode 100644 index 0000000..162fe27 --- /dev/null +++ b/src/main/java/com/google/firebase/auth/PhoneAuthProvider.kt @@ -0,0 +1,73 @@ +package com.google.firebase.auth + +import android.app.Activity +import com.google.firebase.FirebaseException +import java.util.concurrent.TimeUnit + +/** + * Phone number sign-in, mirroring the Android class. The JVM port exchanges a verification id and SMS code it is given + * ([getCredential]) but cannot run a verification itself: that needs reCAPTCHA or Play Integrity, so [verifyPhoneNumber] + * reports a failure to the callbacks. + */ +class PhoneAuthProvider private constructor() { + + @Deprecated("Use PhoneAuthProvider.verifyPhoneNumber(PhoneAuthOptions)") + fun verifyPhoneNumber( + phoneNumber: String, + timeout: Long, + unit: TimeUnit, + activity: Activity, + callbacks: OnVerificationStateChangedCallbacks + ) { + callbacks.onVerificationFailed(FirebaseException(VERIFICATION_UNSUPPORTED)) + } + + @Deprecated("Use PhoneAuthProvider.verifyPhoneNumber(PhoneAuthOptions)") + fun verifyPhoneNumber( + phoneNumber: String, + timeout: Long, + unit: TimeUnit, + activity: Activity, + callbacks: OnVerificationStateChangedCallbacks, + forceResendingToken: ForceResendingToken? + ) { + callbacks.onVerificationFailed(FirebaseException(VERIFICATION_UNSUPPORTED)) + } + + abstract class OnVerificationStateChangedCallbacks { + open fun onCodeAutoRetrievalTimeOut(verificationId: String) {} + + open fun onCodeSent(verificationId: String, forceResendingToken: ForceResendingToken) {} + + abstract fun onVerificationCompleted(credential: PhoneAuthCredential) + + abstract fun onVerificationFailed(exception: FirebaseException) + } + + class ForceResendingToken + + companion object { + const val PROVIDER_ID = "phone" + const val PHONE_SIGN_IN_METHOD = "phone" + + internal const val VERIFICATION_UNSUPPORTED = "Phone number verification is not supported by firebase-java-sdk" + + @JvmStatic + fun getCredential(verificationId: String, smsCode: String): PhoneAuthCredential = PhoneAuthCredential(verificationId, smsCode) + + @JvmStatic + @Deprecated("Use the static PhoneAuthProvider.verifyPhoneNumber(PhoneAuthOptions)") + fun getInstance(): PhoneAuthProvider = PhoneAuthProvider() + + @JvmStatic + @Deprecated("Use the static PhoneAuthProvider.verifyPhoneNumber(PhoneAuthOptions)") + fun getInstance(auth: FirebaseAuth): PhoneAuthProvider = PhoneAuthProvider() + + /** Reports [VERIFICATION_UNSUPPORTED] to the options' callbacks, as the JVM cannot verify a phone number. */ + @JvmStatic + fun verifyPhoneNumber(options: PhoneAuthOptions) { + val callbacks = options.callbacks ?: throw UnsupportedOperationException(VERIFICATION_UNSUPPORTED) + callbacks.onVerificationFailed(FirebaseException(VERIFICATION_UNSUPPORTED)) + } + } +} diff --git a/src/main/java/com/google/firebase/auth/Stubs.kt b/src/main/java/com/google/firebase/auth/Stubs.kt index e17b75a..3558b3f 100644 --- a/src/main/java/com/google/firebase/auth/Stubs.kt +++ b/src/main/java/com/google/firebase/auth/Stubs.kt @@ -1,78 +1,27 @@ package com.google.firebase.auth -import android.net.Uri -import com.google.android.gms.tasks.Task - -class ActionCodeSettings { - companion object { - fun newBuilder(): Builder = TODO() - } - - class Builder { - fun setAndroidPackageName(packageName: String, installIfNotAvailable: Boolean, minimumVersion: String?): Builder = TODO() - fun setDynamicLinkDomain(dynamicLinkDomain: String): Builder = TODO() - fun setIOSBundleId(iOSBundleId: String): Builder = TODO() - fun setUrl(url: String): Builder = TODO() - fun setHandleCodeInApp(canHandleCodeInApp: Boolean): Builder = TODO() - fun build(): ActionCodeSettings = TODO() - } -} - -class FirebaseAuthMultiFactorException(errorCode: String, detailMessage: String) : FirebaseAuthException(errorCode, detailMessage) - -class UserInfo internal constructor( - val displayName: String?, - val email: String?, - val phoneNumber: String?, - photoUrl: String?, - val providerId: String, - val uid: String -) { - val photoUrl: Uri? = photoUrl?.let(Uri::parse) -} - class FirebaseUserMetadata internal constructor( val creationTimestamp: Long, val lastSignInTimestamp: Long ) -class MultiFactor { - val uid: String get() = TODO() - val enrolledFactors: List get() = TODO() - val session: Task get() = TODO() - fun enroll(multiFactorAssertion: MultiFactorAssertion, displayName: String?): Task = TODO() - fun unenroll(multiFactorInfo: MultiFactorInfo): Task = TODO() - fun unenroll(factorUid: String): Task = TODO() -} -class MultiFactorInfo { - val displayName: String? get() = TODO() - val enrollmentTimestamp: Long get() = TODO() - val factorId: String get() = TODO() - val uid: String get() = TODO() -} -class MultiFactorAssertion { - val factorId: String get() = TODO() -} -class MultiFactorSession -class MultiFactorResolver { - val firebaseAuth: FirebaseAuth get() = TODO() - val hints: List get() = TODO() - val session: MultiFactorSession get() = TODO() - fun resolveSignIn(assertion: MultiFactorAssertion): Task = TODO() +interface SignInMethodQueryResult { + val signInMethods: List } -class PhoneAuthCredential internal constructor( - internal val verificationId: String, - internal val smsCode: String -) : AuthCredential("phone") { - init { - require(verificationId.isNotBlank()) { "verificationId must not be blank" } - require(smsCode.isNotBlank()) { "smsCode must not be blank" } +internal class SignInMethodQueryResultImpl(override val signInMethods: List) : SignInMethodQueryResult + +internal class FirebaseAuthSettingsImpl : FirebaseAuthSettings() { + internal var appVerificationDisabledForTesting = false + internal var forceRecaptchaFlowForTesting = false + + override fun forceRecaptchaFlowForTesting(forceRecaptchaFlow: Boolean) { + forceRecaptchaFlowForTesting = forceRecaptchaFlow } - override fun toString(): String = "PhoneAuthCredential{provider='phone'}" -} + override fun setAppVerificationDisabledForTesting(disabled: Boolean) { + appVerificationDisabledForTesting = disabled + } -interface SignInMethodQueryResult { - val signInMethods: List + override fun setAutoRetrievedSmsCodeForPhoneNumber(phoneNumber: String?, smsCode: String?) = Unit } diff --git a/src/main/java/com/google/firebase/auth/TwitterAuthCredential.java b/src/main/java/com/google/firebase/auth/TwitterAuthCredential.java new file mode 100644 index 0000000..492569b --- /dev/null +++ b/src/main/java/com/google/firebase/auth/TwitterAuthCredential.java @@ -0,0 +1,31 @@ +package com.google.firebase.auth; + +public class TwitterAuthCredential extends AuthCredential { + private final String token; + private final String secret; + + TwitterAuthCredential(String token, String secret) { + this.token = requireValue(token, "token"); + this.secret = requireValue(secret, "secret"); + } + + @Override + public String getProvider() { + return TwitterAuthProvider.PROVIDER_ID; + } + + @Override + public String getSignInMethod() { + return TwitterAuthProvider.TWITTER_SIGN_IN_METHOD; + } + + @Override + String accessToken() { + return token; + } + + @Override + String oauthTokenSecret() { + return secret; + } +} diff --git a/src/main/java/com/google/firebase/auth/TwitterAuthProvider.java b/src/main/java/com/google/firebase/auth/TwitterAuthProvider.java index cf04bc4..2878aa4 100644 --- a/src/main/java/com/google/firebase/auth/TwitterAuthProvider.java +++ b/src/main/java/com/google/firebase/auth/TwitterAuthProvider.java @@ -1,9 +1,13 @@ package com.google.firebase.auth; -import kotlin.NotImplementedError; - public class TwitterAuthProvider { - public static AuthCredential getCredential(String email, String password) { - throw new NotImplementedError(); + public static final String PROVIDER_ID = "twitter.com"; + public static final String TWITTER_SIGN_IN_METHOD = "twitter.com"; + + private TwitterAuthProvider() { + } + + public static AuthCredential getCredential(String token, String secret) { + return new TwitterAuthCredential(token, secret); } } diff --git a/src/main/java/com/google/firebase/auth/UserInfo.kt b/src/main/java/com/google/firebase/auth/UserInfo.kt new file mode 100644 index 0000000..961fe3a --- /dev/null +++ b/src/main/java/com/google/firebase/auth/UserInfo.kt @@ -0,0 +1,26 @@ +package com.google.firebase.auth + +import android.net.Uri + +/** A user's profile with one provider, mirroring the Android interface; [FirebaseUser] is the account's own. */ +interface UserInfo { + val displayName: String? + val email: String? + val phoneNumber: String? + val photoUrl: Uri? + val providerId: String + val uid: String + val isEmailVerified: Boolean +} + +internal data class ProviderUserInfo( + override val displayName: String?, + override val email: String?, + override val phoneNumber: String?, + private val photoUrlString: String?, + override val providerId: String, + override val uid: String, + override val isEmailVerified: Boolean +) : UserInfo { + override val photoUrl: Uri? get() = photoUrlString?.let(Uri::parse) +} diff --git a/src/main/java/com/google/firebase/auth/UserProfileChangeRequest.kt b/src/main/java/com/google/firebase/auth/UserProfileChangeRequest.kt index 885e53a..5c3ed3e 100644 --- a/src/main/java/com/google/firebase/auth/UserProfileChangeRequest.kt +++ b/src/main/java/com/google/firebase/auth/UserProfileChangeRequest.kt @@ -5,9 +5,11 @@ import android.os.Parcel import android.os.Parcelable class UserProfileChangeRequest private constructor( - internal val displayName: String?, + val displayName: String?, internal val photoUrl: String? ) : Parcelable { + val photoUri: Uri? get() = photoUrl?.let(Uri::parse) + override fun describeContents(): Int = displayName.hashCode() + photoUrl.hashCode() override fun writeToParcel( @@ -42,6 +44,10 @@ class UserProfileChangeRequest private constructor( return this } + fun getDisplayName(): String? = displayName + + fun getPhotoUri(): Uri? = photoUri + fun build(): UserProfileChangeRequest = UserProfileChangeRequest(displayName, photoUri?.toString()) } } diff --git a/src/test/kotlin/FirebaseAuthApiTest.kt b/src/test/kotlin/FirebaseAuthApiTest.kt new file mode 100644 index 0000000..f9a9889 --- /dev/null +++ b/src/test/kotlin/FirebaseAuthApiTest.kt @@ -0,0 +1,218 @@ +/* + * Exercises the parts of the Firebase Auth API that need no server: the Android SDK's shapes, constants, builders, + * credential types and the settings FirebaseAuth keeps. + */ +import android.app.Activity +import android.net.Uri +import com.google.firebase.FirebaseException +import com.google.firebase.auth.ActionCodeResult +import com.google.firebase.auth.ActionCodeSettings +import com.google.firebase.auth.ActionCodeUrl +import com.google.firebase.auth.EmailAuthCredential +import com.google.firebase.auth.EmailAuthProvider +import com.google.firebase.auth.FacebookAuthCredential +import com.google.firebase.auth.FacebookAuthProvider +import com.google.firebase.auth.FederatedAuthProvider +import com.google.firebase.auth.FirebaseAuth +import com.google.firebase.auth.FirebaseAuthMissingActivityForRecaptchaException +import com.google.firebase.auth.FirebaseAuthProvider +import com.google.firebase.auth.FirebaseAuthUserCollisionException +import com.google.firebase.auth.FirebaseAuthWeakPasswordException +import com.google.firebase.auth.GithubAuthProvider +import com.google.firebase.auth.MultiFactorInfo +import com.google.firebase.auth.OAuthCredential +import com.google.firebase.auth.OAuthProvider +import com.google.firebase.auth.PhoneAuthCredential +import com.google.firebase.auth.PhoneAuthOptions +import com.google.firebase.auth.PhoneAuthProvider +import com.google.firebase.auth.PhoneMultiFactorGenerator +import com.google.firebase.auth.TotpMultiFactorGenerator +import com.google.firebase.auth.TwitterAuthProvider +import com.google.firebase.auth.UserProfileChangeRequest +import kotlinx.coroutines.tasks.await +import kotlinx.coroutines.test.runTest +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertThrows +import org.junit.Assert.assertTrue +import org.junit.Assert.fail +import org.junit.Test +import java.net.URLEncoder +import java.util.Locale +import java.util.concurrent.TimeUnit + +class FirebaseAuthApiTest : FirebaseTest() { + private val auth by lazy { FirebaseAuth.getInstance(app) } + + @Test + fun `action code settings carry their fields`() { + val settings = + ActionCodeSettings + .newBuilder() + .setUrl("https://example.com/finish") + .setHandleCodeInApp(true) + .setIOSBundleId("com.example.ios") + .setAndroidPackageName("com.example", true, "12") + .setLinkDomain("example.page.link") + .build() + assertEquals("https://example.com/finish", settings.getUrl()) + assertTrue(settings.canHandleCodeInApp()) + assertEquals("com.example.ios", settings.getIOSBundle()) + assertEquals("com.example", settings.getAndroidPackageName()) + assertTrue(settings.getAndroidInstallApp()) + assertEquals("12", settings.getAndroidMinimumVersion()) + assertEquals("example.page.link", settings.getLinkDomain()) + + val builder = ActionCodeSettings.newBuilder().setUrl("https://example.com") + assertEquals("https://example.com", builder.getUrl()) + assertFalse(builder.getHandleCodeInApp()) + assertNull(builder.getLinkDomain()) + assertThrows(IllegalArgumentException::class.java) { ActionCodeSettings.newBuilder().build() } + } + + @Test + fun `action links are parsed, unwrapping dynamic links`() { + val link = + "https://fir-java-sdk.firebaseapp.com/__/auth/action?mode=resetPassword&oobCode=abc123&apiKey=key" + + "&continueUrl=https%3A%2F%2Fexample.com%2Ffinish&lang=en" + val url = ActionCodeUrl.parseLink(link)!! + assertEquals(ActionCodeResult.PASSWORD_RESET, url.operation) + assertEquals("abc123", url.code) + assertEquals("key", url.apiKey) + assertEquals("https://example.com/finish", url.continueUrl) + assertEquals("en", url.languageCode) + + val inner = "https://fir-java-sdk.firebaseapp.com/__/auth/action?mode=signIn&oobCode=xyz" + val wrapped = "https://example.page.link/?link=" + URLEncoder.encode(inner, "UTF-8") + assertEquals(ActionCodeResult.SIGN_IN_WITH_EMAIL_LINK, ActionCodeUrl.parseLink(wrapped)!!.operation) + assertTrue(auth.isSignInWithEmailLink(wrapped)) + assertFalse(auth.isSignInWithEmailLink(link)) + assertNull(ActionCodeUrl.parseLink("https://example.com/")) + assertNull(ActionCodeUrl.parseLink("not a url")) + } + + @Test + fun `providers expose the android constants and credential types`() { + assertEquals("password", EmailAuthProvider.PROVIDER_ID) + assertEquals("emailLink", EmailAuthProvider.EMAIL_LINK_SIGN_IN_METHOD) + assertEquals("facebook.com", FacebookAuthProvider.PROVIDER_ID) + assertEquals("github.com", GithubAuthProvider.GITHUB_SIGN_IN_METHOD) + assertEquals("twitter.com", TwitterAuthProvider.TWITTER_SIGN_IN_METHOD) + assertEquals("phone", PhoneAuthProvider.PHONE_SIGN_IN_METHOD) + assertEquals("firebase", FirebaseAuthProvider.PROVIDER_ID) + assertEquals("factorIdKey", MultiFactorInfo.FACTOR_ID_KEY) + + val email = EmailAuthProvider.getCredential("a@b.c", "secret") + assertTrue(email is EmailAuthCredential) + assertEquals("password", email.provider) + assertEquals("password", email.signInMethod) + assertFalse(email.toString().contains("secret")) + val link = EmailAuthProvider.getCredentialWithLink("a@b.c", "https://x/?mode=signIn&oobCode=code1") + assertEquals("emailLink", link.signInMethod) + assertThrows(IllegalArgumentException::class.java) { EmailAuthProvider.getCredentialWithLink("a@b.c", "https://x/") } + + assertTrue(FacebookAuthProvider.getCredential("token") is FacebookAuthCredential) + assertEquals("github.com", GithubAuthProvider.getCredential("token").provider) + val twitter = TwitterAuthProvider.getCredential("token", "secret") + assertEquals("twitter.com", twitter.provider) + assertFalse(twitter.toString().contains("secret")) + + val phone = PhoneAuthProvider.getCredential("verification", "123456") + assertEquals("123456", phone.smsCode) + assertEquals("phone", phone.signInMethod) + } + + @Test + fun `oauth builders expose their state`() { + val builder = OAuthProvider.newBuilder("apple.com", auth).setScopes(listOf("email")).addCustomParameter("locale", "fr") + assertEquals(listOf("email"), builder.scopes) + val provider = builder.build() + assertEquals("apple.com", provider.providerId) + assertEquals(mapOf("locale" to "fr"), provider.customParameters) + assertTrue(provider is FederatedAuthProvider) + + val credentialBuilder = OAuthProvider.newCredentialBuilder("apple.com").setIdToken("id").setAccessToken("access") + assertEquals("id", credentialBuilder.idToken) + assertEquals("access", credentialBuilder.accessToken) + val credential = credentialBuilder.build() as OAuthCredential + assertEquals("id", credential.idToken) + assertEquals("access", credential.accessToken) + assertNull(credential.secret) + } + + @Test + fun `profile change requests expose their fields`() { + val request = UserProfileChangeRequest.Builder().setDisplayName("Name").setPhotoUri(Uri.parse("https://example.com/p.png")).build() + assertEquals("Name", request.displayName) + assertEquals("https://example.com/p.png", request.photoUri.toString()) + val builder = UserProfileChangeRequest.Builder().setDisplayName("Other") + assertEquals("Other", builder.getDisplayName()) + assertNull(builder.getPhotoUri()) + } + + @Test + fun `auth keeps language, tenant and auth domain settings`() = + runTest { + assertNull(auth.languageCode) + auth.languageCode = "de" + assertEquals("de", auth.languageCode) + auth.useAppLanguage() + assertEquals(Locale.getDefault().toLanguageTag(), auth.languageCode) + auth.languageCode = null + + auth.tenantId = "tenant" + assertEquals("tenant", auth.tenantId) + auth.tenantId = null + auth.customAuthDomain = "auth.example.com" + assertEquals("auth.example.com", auth.customAuthDomain) + + assertNull(auth.pendingAuthResult) + assertNotNull(auth.firebaseAuthSettings) + auth.firebaseAuthSettings.setAppVerificationDisabledForTesting(true) + auth.initializeRecaptchaConfig().await() + } + + @Test + fun `exceptions carry the android details`() { + val collision = FirebaseAuthUserCollisionException("ERROR_EMAIL_ALREADY_IN_USE", "exists") + assertNull(collision.getEmail()) + assertNull(collision.getUpdatedCredential()) + assertEquals("too short", FirebaseAuthWeakPasswordException("ERROR_WEAK_PASSWORD", "weak", "too short").getReason()) + assertNull(FirebaseAuthWeakPasswordException("ERROR_WEAK_PASSWORD", "weak").getReason()) + assertEquals("ERROR_MISSING_ACTIVITY", FirebaseAuthMissingActivityForRecaptchaException().errorCode) + } + + @Test + fun `phone verification reports that it is unsupported`() { + var failure: FirebaseException? = null + val options = + PhoneAuthOptions + .newBuilder(auth) + .setPhoneNumber("+15555550100") + .setTimeout(30L, TimeUnit.SECONDS) + .setCallbacks( + object : PhoneAuthProvider.OnVerificationStateChangedCallbacks() { + override fun onVerificationCompleted(credential: PhoneAuthCredential) = fail("the JVM cannot verify a phone number") + + override fun onVerificationFailed(exception: FirebaseException) { + failure = exception + } + } + ).build() + PhoneAuthProvider.verifyPhoneNumber(options) + assertNotNull(failure) + assertThrows(IllegalArgumentException::class.java) { PhoneAuthOptions.newBuilder(auth).setPhoneNumber("+1").build() } + + assertEquals("phone", PhoneMultiFactorGenerator.getAssertion(PhoneAuthProvider.getCredential("v", "1")).factorId) + assertEquals("totp", TotpMultiFactorGenerator.getAssertionForSignIn("enrollment", "000000").factorId) + } + + @Test + fun `activity flows fail on the jvm`() { + val task = auth.startActivityForSignInWithProvider(Activity(), OAuthProvider.newBuilder("apple.com", auth).build()) + assertTrue(task.isComplete) + assertTrue(task.exception is UnsupportedOperationException) + } +} diff --git a/src/test/kotlin/FirebaseAuthEmailFlowsTest.kt b/src/test/kotlin/FirebaseAuthEmailFlowsTest.kt new file mode 100644 index 0000000..cd2c964 --- /dev/null +++ b/src/test/kotlin/FirebaseAuthEmailFlowsTest.kt @@ -0,0 +1,124 @@ +/* + * The email action-code flows against the Auth emulator, whose REST API hands out the codes it would have emailed. + */ +import com.google.firebase.auth.ActionCodeResult +import com.google.firebase.auth.ActionCodeSettings +import com.google.firebase.auth.EmailAuthProvider +import com.google.firebase.auth.FirebaseAuth +import kotlinx.coroutines.tasks.await +import kotlinx.coroutines.test.runTest +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.booleanOrNull +import kotlinx.serialization.json.jsonArray +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import java.net.HttpURLConnection +import java.net.URL +import java.util.UUID + +class FirebaseAuthEmailFlowsTest : FirebaseTest() { + private val email = "flows${UUID.randomUUID()}@example.com" + private val auth by lazy { FirebaseAuth.getInstance(app) } + private val emulator = "http://localhost:9099" + + @Before + fun initialize() { + auth.useEmulator("localhost", 9099) + } + + private fun oobCodes(): List = + URL("$emulator/emulator/v1/projects/${options.projectId}/oobCodes").openStream().use { stream -> + Json.parseToJsonElement(stream.readBytes().decodeToString()).jsonObject["oobCodes"]!!.jsonArray.map { it.jsonObject } + } + + private fun latestCode(requestType: String): JsonObject = + oobCodes().last { it["email"]?.jsonPrimitive?.content == email && it["requestType"]?.jsonPrimitive?.content == requestType } + + private fun lookupEmailVerified(idToken: String): Boolean { + val connection = URL("$emulator/identitytoolkit.googleapis.com/v1/accounts:lookup?key=${options.apiKey}").openConnection() as HttpURLConnection + connection.requestMethod = "POST" + connection.doOutput = true + connection.setRequestProperty("Content-Type", "application/json") + connection.outputStream.use { it.write(JsonObject(mapOf("idToken" to JsonPrimitive(idToken))).toString().toByteArray()) } + val body = connection.inputStream.use { it.readBytes().decodeToString() } + return Json.parseToJsonElement(body).jsonObject["users"]!!.jsonArray.first().jsonObject["emailVerified"]?.jsonPrimitive?.booleanOrNull ?: false + } + + @Test + fun `a password reset code is checked, verified and confirmed`() = + runTest { + auth.createUserWithEmailAndPassword(email, "oldpass1").await() + auth.signOut() + auth.sendPasswordResetEmail(email).await() + val code = latestCode("PASSWORD_RESET")["oobCode"]!!.jsonPrimitive.content + + val result = auth.checkActionCode(code).await() + assertEquals(ActionCodeResult.PASSWORD_RESET, result.operation) + assertEquals(email, result.info?.email) + assertEquals(email, auth.verifyPasswordResetCode(code).await()) + auth.confirmPasswordReset(code, "newpass2").await() + assertEquals(email, auth.signInWithEmailAndPassword(email, "newpass2").await().user?.email) + } + + @Test + fun `an email link signs its address in`() = + runTest { + val settings = ActionCodeSettings.newBuilder().setUrl("https://example.com/finish").setHandleCodeInApp(true).build() + auth.sendSignInLinkToEmail(email, settings).await() + val link = latestCode("EMAIL_SIGNIN")["oobLink"]!!.jsonPrimitive.content + + assertTrue(auth.isSignInWithEmailLink(link)) + val result = auth.signInWithEmailLink(email, link).await() + assertEquals(email, result.user?.email) + assertTrue(result.additionalUserInfo!!.isNewUser) + assertEquals(email, auth.currentUser?.email) + assertTrue(auth.currentUser!!.providerData.any { it.providerId == EmailAuthProvider.PROVIDER_ID }) + } + + @Test + fun `an email verification code verifies the address`() = + runTest { + val user = auth.createUserWithEmailAndPassword(email, "pass1234").await().user!! + assertFalse(user.isEmailVerified) + user.sendEmailVerification().await() + val code = latestCode("VERIFY_EMAIL")["oobCode"]!!.jsonPrimitive.content + assertEquals(ActionCodeResult.VERIFY_EMAIL, auth.checkActionCode(code).await().operation) + auth.applyActionCode(code).await() + assertTrue(lookupEmailVerified(user.getIdToken(false).await().token!!)) + } + + @Test + fun `an email credential links to an anonymous account and signs in again`() = + runTest { + val anonymous = auth.signInAnonymously().await().user!! + val linked = anonymous.linkWithCredential(EmailAuthProvider.getCredential(email, "linkpass1")).await() + assertEquals(anonymous.uid, linked.user!!.uid) + assertEquals(email, linked.user!!.email) + assertFalse(linked.user!!.isAnonymous) + + auth.signOut() + val signedIn = auth.signInWithCredential(EmailAuthProvider.getCredential(email, "linkpass1")).await() + assertEquals(anonymous.uid, signedIn.user!!.uid) + assertFalse(signedIn.additionalUserInfo!!.isNewUser) + @Suppress("DEPRECATION") + assertEquals(listOf(EmailAuthProvider.EMAIL_PASSWORD_SIGN_IN_METHOD), auth.fetchSignInMethodsForEmail(email).await().signInMethods) + } + + @Test + fun `updateCurrentUser restores a signed-out user`() = + runTest { + val user = auth.createUserWithEmailAndPassword(email, "pass1234").await().user!! + auth.signOut() + assertNull(auth.currentUser) + auth.updateCurrentUser(user).await() + assertEquals(user.uid, auth.currentUser?.uid) + } +} diff --git a/src/test/kotlin/FirebaseAuthTest.kt b/src/test/kotlin/FirebaseAuthTest.kt index dde3b18..2ff3734 100644 --- a/src/test/kotlin/FirebaseAuthTest.kt +++ b/src/test/kotlin/FirebaseAuthTest.kt @@ -86,7 +86,7 @@ class FirebaseAuthTest : FirebaseTest() { .build() )?.await() assertEquals("testDisplayName", auth.currentUser?.displayName) - assertEquals("https://picsum.photos/100", auth.currentUser?.photoUrl) + assertEquals("https://picsum.photos/100", auth.currentUser?.photoUrl?.toString()) } @Test From 61ad2734e8305ed3ae7e5d0705c4d8c918dbd5c3 Mon Sep 17 00:00:00 2001 From: Nick Williams Date: Sat, 31 Oct 2026 04:49:21 +0000 Subject: [PATCH 2/4] Address the review of the Auth API alignment The new operations complete with null as Task, as the Android SDK's do, and verifyBeforeUpdateEmail joins them through sendOobCode, so the locale header reaches every action email. An action sent for a user, a phone number link and an Apple token revocation first refresh the user's ID token when it has expired. Linking a password credential to an account that already has a password provider fails with ERROR_PROVIDER_ALREADY_LINKED instead of replacing the password, an email-link credential is only created from a sign-in link, verifyPasswordResetCode rejects codes of other actions, updateCurrentUser rejects a user whose token was issued for another project, signInWithCustomToken keeps the sign-in's additional user info, and AuthResult no longer renders the user, whose string form carries its tokens. --- .../google/firebase/auth/AuthResultImpl.kt | 5 +- .../firebase/auth/EmailAuthProvider.java | 2 +- .../com/google/firebase/auth/FirebaseAuth.kt | 173 +++++++++--------- .../com/google/firebase/auth/FirebaseUser.kt | 10 +- src/test/kotlin/FirebaseAuthApiTest.kt | 1 + src/test/kotlin/FirebaseAuthEmailFlowsTest.kt | 9 + 6 files changed, 104 insertions(+), 96 deletions(-) diff --git a/src/main/java/com/google/firebase/auth/AuthResultImpl.kt b/src/main/java/com/google/firebase/auth/AuthResultImpl.kt index 7d792b5..2cc5d71 100644 --- a/src/main/java/com/google/firebase/auth/AuthResultImpl.kt +++ b/src/main/java/com/google/firebase/auth/AuthResultImpl.kt @@ -12,7 +12,7 @@ import kotlinx.serialization.json.jsonObject import kotlinx.serialization.json.jsonPrimitive import kotlinx.serialization.json.longOrNull -internal data class AuthResultImpl( +internal class AuthResultImpl( private val user: FirebaseUser?, private val additionalUserInfo: AdditionalUserInfo?, private val credential: AuthCredential? @@ -22,6 +22,9 @@ internal data class AuthResultImpl( override fun getAdditionalUserInfo(): AdditionalUserInfo? = additionalUserInfo override fun getCredential(): AuthCredential? = credential + + /** Names the user without rendering it: the user's string form carries its tokens. */ + override fun toString(): String = "AuthResult{uid=${user?.uid}, provider=${additionalUserInfo?.providerId}}" } /** What a sign-in response says about the account beyond the user: provider, raw profile and whether it was created. */ diff --git a/src/main/java/com/google/firebase/auth/EmailAuthProvider.java b/src/main/java/com/google/firebase/auth/EmailAuthProvider.java index 235108e..9c34e81 100644 --- a/src/main/java/com/google/firebase/auth/EmailAuthProvider.java +++ b/src/main/java/com/google/firebase/auth/EmailAuthProvider.java @@ -14,7 +14,7 @@ public static AuthCredential getCredential(String email, String password) { public static AuthCredential getCredentialWithLink(String email, String emailLink) { ActionCodeUrl url = ActionCodeUrl.parseLink(AuthCredential.requireValue(emailLink, "emailLink")); - if (url == null || url.getCode() == null) { + if (url == null || url.getCode() == null || url.getOperation() != ActionCodeResult.SIGN_IN_WITH_EMAIL_LINK) { throw new IllegalArgumentException( "Given link is not a valid email link. Please use FirebaseAuth#isSignInWithEmailLink(String) to determine this before calling this function" ); diff --git a/src/main/java/com/google/firebase/auth/FirebaseAuth.kt b/src/main/java/com/google/firebase/auth/FirebaseAuth.kt index 82f9bc0..58af8a0 100644 --- a/src/main/java/com/google/firebase/auth/FirebaseAuth.kt +++ b/src/main/java/com/google/firebase/auth/FirebaseAuth.kt @@ -1,5 +1,6 @@ package com.google.firebase.auth +import android.app.Activity import android.net.Uri import android.util.Log import com.google.android.gms.tasks.Task @@ -13,7 +14,6 @@ import com.google.firebase.auth.internal.InternalAuthProvider import com.google.firebase.internal.InternalTokenResult import com.google.firebase.internal.api.FirebaseNoSignedInUserException import kotlinx.coroutines.launch -import android.app.Activity import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable import kotlinx.serialization.Transient @@ -192,55 +192,14 @@ data class FirebaseUserImpl internal constructor( override fun verifyBeforeUpdateEmail( newEmail: String, actionCodeSettings: ActionCodeSettings? - ): Task { - val source = TaskCompletionSource() - val body = - JsonObject( - mapOf( - "idToken" to JsonPrimitive(idToken), - "email" to JsonPrimitive(email), - "newEmail" to JsonPrimitive(newEmail), - "requestType" to JsonPrimitive(OobRequestType.VERIFY_AND_CHANGE_EMAIL.name) - ) + actionCodeSettings?.toRequestFields().orEmpty() - ).toString().toRequestBody(FirebaseAuth.getInstance(app).json) - val request = - Request - .Builder() - .url(urlFactory.buildUrl("identitytoolkit.googleapis.com/v1/accounts:sendOobCode")) - .post(body) - .build() - FirebaseAuth.getInstance(app).client.newCall(request).enqueue( - object : Callback { - override fun onFailure( - call: Call, - e: IOException - ) { - source.setException(FirebaseException(e.toString(), e)) - e.printStackTrace() - } - - @Throws(IOException::class) - override fun onResponse( - call: Call, - response: Response - ) { - if (!response.isSuccessful) { - FirebaseAuth.getInstance(app).signOut() - source.setException( - FirebaseAuth.getInstance(app).createAuthInvalidUserException( - "verifyEmail", - request, - response - ) - ) - } else { - source.setResult(null) - } - } - } + ): Task = + FirebaseAuth.getInstance(app).sendOobCode( + "verifyEmail", + this, + OobRequestType.VERIFY_AND_CHANGE_EMAIL, + mapOf("email" to JsonPrimitive(email), "newEmail" to JsonPrimitive(newEmail)), + actionCodeSettings ) - return source.task - } override fun getIdToken(forceRefresh: Boolean) = FirebaseAuth.getInstance(app).getAccessToken(forceRefresh) @@ -249,15 +208,10 @@ data class FirebaseUserImpl internal constructor( override fun linkWithCredential(credential: AuthCredential): Task = FirebaseAuth.getInstance(app).linkWithCredential(this, credential) - override fun sendEmailVerification(actionCodeSettings: ActionCodeSettings?): Task = - FirebaseAuth.getInstance(app).sendOobCode( - "sendEmailVerification", - OobRequestType.VERIFY_EMAIL, - mapOf("idToken" to JsonPrimitive(idToken)), - actionCodeSettings - ) + override fun sendEmailVerification(actionCodeSettings: ActionCodeSettings?): Task = + FirebaseAuth.getInstance(app).sendOobCode("sendEmailVerification", this, OobRequestType.VERIFY_EMAIL, emptyMap(), actionCodeSettings) - override fun updatePhoneNumber(credential: PhoneAuthCredential): Task = + override fun updatePhoneNumber(credential: PhoneAuthCredential): Task = FirebaseAuth.getInstance(app).updatePhoneNumber(this, credential) fun updateProfile( @@ -453,7 +407,9 @@ class FirebaseAuth constructor( FirebaseUserImpl(app, jsonParser.parseToJsonElement(responseBody).jsonObject, urlFactory = urlFactory) } ) - return source.task.onSuccessTask { updateByGetAccountInfo() } + return source.task.onSuccessTask { signIn -> + updateByGetAccountInfo().onSuccessTask { Tasks.forResult(AuthResultImpl(user, signIn?.additionalUserInfo, signIn?.credential)) } + } } private fun updateByGetAccountInfo(): Task { @@ -912,23 +868,40 @@ class FirebaseAuth constructor( user = user?.copy(urlFactory = urlFactory) } - fun sendPasswordResetEmail(email: String): Task = sendPasswordResetEmail(email, null) + fun sendPasswordResetEmail(email: String): Task = sendPasswordResetEmail(email, null) - fun sendPasswordResetEmail(email: String, settings: ActionCodeSettings?): Task = - sendOobCode("sendPasswordResetEmail", OobRequestType.PASSWORD_RESET, mapOf("email" to JsonPrimitive(email)), settings) + fun sendPasswordResetEmail(email: String, settings: ActionCodeSettings?): Task = + sendOobCode("sendPasswordResetEmail", null, OobRequestType.PASSWORD_RESET, mapOf("email" to JsonPrimitive(email)), settings) - /** Posts [fields] with [type] to `accounts:sendOobCode`, the request behind every action email. */ + /** + * Posts [fields] with [type] to `accounts:sendOobCode`, the request behind every action email, with [user]'s ID + * token (refreshed if it has expired) when the action concerns a signed-in account. + */ internal fun sendOobCode( action: String, + user: FirebaseUserImpl?, type: OobRequestType, fields: Map, settings: ActionCodeSettings? - ): Task = - postJson( - action, - "identitytoolkit.googleapis.com/v1/accounts:sendOobCode", - JsonObject(mapOf("requestType" to JsonPrimitive(type.name)) + fields + settings?.toRequestFields().orEmpty()) - ).onSuccessTask { Tasks.forResult(Unit) } + ): Task { + val body = mapOf("requestType" to JsonPrimitive(type.name)) + fields + settings?.toRequestFields().orEmpty() + val url = "identitytoolkit.googleapis.com/v1/accounts:sendOobCode" + val sent = + if (user == null) { + postJson(action, url, JsonObject(body)) + } else { + freshIdToken(user).onSuccessTask { idToken -> postJson(action, url, JsonObject(body + ("idToken" to JsonPrimitive(idToken)))) } + } + return sent.onSuccessTask { Tasks.forResult(null) } + } + + /** [user]'s ID token, refreshed through [getAccessToken] when it is the current user's and has expired. */ + internal fun freshIdToken(user: FirebaseUserImpl): Task = + if (this.user?.uid == user.uid) { + getAccessToken(false).onSuccessTask { result -> Tasks.forResult(requireNotNull(result?.token) { "No ID token for the current user" }) } + } else { + Tasks.forResult(user.idToken) + } /** * Posts [body] to [url] and completes with the parsed response, or with the error [createAuthInvalidUserException] @@ -1006,7 +979,8 @@ class FirebaseAuth constructor( internal fun updatePhoneNumber( currentUser: FirebaseUserImpl, credential: PhoneAuthCredential - ): Task = linkWithCredential(currentUser, credential).onSuccessTask { Tasks.forResult(Unit) } + ): Task = linkWithCredential(currentUser, credential).onSuccessTask { Tasks.forResult(null) } + fun signInWithCredential(authCredential: AuthCredential): Task = enqueueCredentialAuthPost(authCredential, currentIdToken = null) { responseBody -> FirebaseUserImpl( @@ -1029,6 +1003,13 @@ class FirebaseAuth constructor( ) ) } + // Linking a password to an account that has one would replace it through accounts:update. + if (authCredential is EmailAuthCredential && authCredential.password != null && EmailAuthProvider.PROVIDER_ID in signedInUser.providerIds) { + return Tasks.forException( + FirebaseAuthUserCollisionException("ERROR_PROVIDER_ALREADY_LINKED", "User has already been linked to the given provider.") + .withDetails(signedInUser.email, null) + ) + } return enqueueCredentialAuthPost(authCredential, currentIdToken = signedInUser.idToken) { responseBody -> val data = jsonParser.parseToJsonElement(responseBody).jsonObject @@ -1109,6 +1090,7 @@ class FirebaseAuth constructor( setResult = setResult ).task } + /** What an action code is for and which account it concerns, from `accounts:resetPassword` called with the code alone. */ fun checkActionCode(code: String): Task = postJson("checkActionCode", "identitytoolkit.googleapis.com/v1/accounts:resetPassword", JsonObject(mapOf("oobCode" to JsonPrimitive(code)))) @@ -1117,22 +1099,28 @@ class FirebaseAuth constructor( fun confirmPasswordReset( code: String, newPassword: String - ): Task = + ): Task = postJson( "confirmPasswordReset", "identitytoolkit.googleapis.com/v1/accounts:resetPassword", JsonObject(mapOf("oobCode" to JsonPrimitive(code), "newPassword" to JsonPrimitive(newPassword))) - ).onSuccessTask { Tasks.forResult(Unit) } + ).onSuccessTask { Tasks.forResult(null) } /** The email a password reset code was issued for, which also checks that the code is valid. */ fun verifyPasswordResetCode(code: String): Task = postJson("verifyPasswordResetCode", "identitytoolkit.googleapis.com/v1/accounts:resetPassword", JsonObject(mapOf("oobCode" to JsonPrimitive(code)))) - .onSuccessTask { data -> Tasks.forResult(requireNotNull(data)["email"]?.jsonPrimitive?.contentOrNull ?: throw FirebaseAuthActionCodeException("ERROR_INVALID_ACTION_CODE", "The action code has no email")) } + .onSuccessTask { data -> + val response = requireNotNull(data) + if (response["requestType"]?.jsonPrimitive?.contentOrNull != OobRequestType.PASSWORD_RESET.name) { + throw FirebaseAuthActionCodeException("ERROR_INVALID_ACTION_CODE", "The action code is not a password reset code") + } + Tasks.forResult(response["email"]?.jsonPrimitive?.contentOrNull ?: throw FirebaseAuthActionCodeException("ERROR_INVALID_ACTION_CODE", "The action code has no email")) + } /** Applies a verification, email recovery or second-factor reversal code. */ - fun applyActionCode(code: String): Task = + fun applyActionCode(code: String): Task = postJson("applyActionCode", "identitytoolkit.googleapis.com/v1/accounts:update", JsonObject(mapOf("oobCode" to JsonPrimitive(code)))) - .onSuccessTask { Tasks.forResult(Unit) } + .onSuccessTask { Tasks.forResult(null) } @Deprecated("Email enumeration protection hides the sign-in methods of other accounts; Firebase recommends against this call") fun fetchSignInMethodsForEmail(email: String): Task = @@ -1149,11 +1137,11 @@ class FirebaseAuth constructor( fun sendSignInLinkToEmail( email: String, actionCodeSettings: ActionCodeSettings - ): Task { + ): Task { if (!actionCodeSettings.canHandleCodeInApp()) { return Tasks.forException(IllegalArgumentException("You must set canHandleCodeInApp in your ActionCodeSettings to true for Email-Link Sign-in.")) } - return sendOobCode("sendSignInLinkToEmail", OobRequestType.EMAIL_SIGNIN, mapOf("email" to JsonPrimitive(email)), actionCodeSettings) + return sendOobCode("sendSignInLinkToEmail", null, OobRequestType.EMAIL_SIGNIN, mapOf("email" to JsonPrimitive(email)), actionCodeSettings) } fun isSignInWithEmailLink(link: String): Boolean = ActionCodeUrl.parseLink(link)?.operation == ActionCodeResult.SIGN_IN_WITH_EMAIL_LINK @@ -1165,11 +1153,16 @@ class FirebaseAuth constructor( signInWithCredential(EmailAuthProvider.getCredentialWithLink(email, link)) /** Makes [user], obtained from this port's own sign-in, the current user. */ - fun updateCurrentUser(user: FirebaseUser): Task { + fun updateCurrentUser(user: FirebaseUser): Task { val restored = user as? FirebaseUserImpl ?: return Tasks.forException(IllegalArgumentException("The user must come from a firebase-java-sdk sign-in")) + if (restored.claims["aud"] != app.options.projectId) { + return Tasks.forException( + FirebaseAuthInvalidUserException("ERROR_INVALID_USER_TOKEN", "The user belongs to a different Firebase project than this app.") + ) + } this.user = restored.copy(app = app, urlFactory = urlFactory) - return Tasks.forResult(Unit) + return Tasks.forResult(null) } /** The language of the emails this instance sends, as the `X-Firebase-Locale` header; null for the project default. */ @@ -1196,20 +1189,22 @@ class FirebaseAuth constructor( /** Revokes an Apple sign-in [token] for the current user, as the Android SDK does before an account deletion. */ fun revokeAccessToken(token: String): Task { - val idToken = user?.idToken + val current = user ?: return Tasks.forException(FirebaseNoSignedInUserException("Please sign in before trying to revoke an access token.")) - return postJson( - "revokeAccessToken", - "identitytoolkit.googleapis.com/v2/accounts:revokeToken", - JsonObject( - mapOf( - "providerId" to JsonPrimitive("apple.com"), - "tokenType" to JsonPrimitive("ACCESS_TOKEN"), - "token" to JsonPrimitive(token), - "idToken" to JsonPrimitive(idToken) + return freshIdToken(current).onSuccessTask { idToken -> + postJson( + "revokeAccessToken", + "identitytoolkit.googleapis.com/v2/accounts:revokeToken", + JsonObject( + mapOf( + "providerId" to JsonPrimitive("apple.com"), + "tokenType" to JsonPrimitive("ACCESS_TOKEN"), + "token" to JsonPrimitive(token), + "idToken" to JsonPrimitive(idToken) + ) ) ) - ).onSuccessTask { Tasks.forResult(null) } + }.onSuccessTask { Tasks.forResult(null) } } fun startActivityForSignInWithProvider( diff --git a/src/main/java/com/google/firebase/auth/FirebaseUser.kt b/src/main/java/com/google/firebase/auth/FirebaseUser.kt index 2413b2b..5b7a6a0 100644 --- a/src/main/java/com/google/firebase/auth/FirebaseUser.kt +++ b/src/main/java/com/google/firebase/auth/FirebaseUser.kt @@ -33,15 +33,15 @@ abstract class FirebaseUser : UserInfo { abstract fun linkWithCredential(credential: AuthCredential): Task - fun verifyBeforeUpdateEmail(newEmail: String): Task = verifyBeforeUpdateEmail(newEmail, null) + fun verifyBeforeUpdateEmail(newEmail: String): Task = verifyBeforeUpdateEmail(newEmail, null) - abstract fun verifyBeforeUpdateEmail(newEmail: String, actionCodeSettings: ActionCodeSettings?): Task + abstract fun verifyBeforeUpdateEmail(newEmail: String, actionCodeSettings: ActionCodeSettings?): Task - fun sendEmailVerification(): Task = sendEmailVerification(null) + fun sendEmailVerification(): Task = sendEmailVerification(null) - abstract fun sendEmailVerification(actionCodeSettings: ActionCodeSettings?): Task + abstract fun sendEmailVerification(actionCodeSettings: ActionCodeSettings?): Task - abstract fun updatePhoneNumber(credential: PhoneAuthCredential): Task + abstract fun updatePhoneNumber(credential: PhoneAuthCredential): Task fun startActivityForLinkWithProvider(activity: Activity, federatedAuthProvider: FederatedAuthProvider): Task = unsupportedTask(ACTIVITY_FLOWS_UNSUPPORTED) diff --git a/src/test/kotlin/FirebaseAuthApiTest.kt b/src/test/kotlin/FirebaseAuthApiTest.kt index f9a9889..5ce3214 100644 --- a/src/test/kotlin/FirebaseAuthApiTest.kt +++ b/src/test/kotlin/FirebaseAuthApiTest.kt @@ -112,6 +112,7 @@ class FirebaseAuthApiTest : FirebaseTest() { val link = EmailAuthProvider.getCredentialWithLink("a@b.c", "https://x/?mode=signIn&oobCode=code1") assertEquals("emailLink", link.signInMethod) assertThrows(IllegalArgumentException::class.java) { EmailAuthProvider.getCredentialWithLink("a@b.c", "https://x/") } + assertThrows(IllegalArgumentException::class.java) { EmailAuthProvider.getCredentialWithLink("a@b.c", "https://x/?mode=resetPassword&oobCode=code1") } assertTrue(FacebookAuthProvider.getCredential("token") is FacebookAuthCredential) assertEquals("github.com", GithubAuthProvider.getCredential("token").provider) diff --git a/src/test/kotlin/FirebaseAuthEmailFlowsTest.kt b/src/test/kotlin/FirebaseAuthEmailFlowsTest.kt index cd2c964..7de129c 100644 --- a/src/test/kotlin/FirebaseAuthEmailFlowsTest.kt +++ b/src/test/kotlin/FirebaseAuthEmailFlowsTest.kt @@ -5,6 +5,9 @@ import com.google.firebase.auth.ActionCodeResult import com.google.firebase.auth.ActionCodeSettings import com.google.firebase.auth.EmailAuthProvider import com.google.firebase.auth.FirebaseAuth +import com.google.firebase.auth.FirebaseAuthActionCodeException +import com.google.firebase.auth.FirebaseAuthUserCollisionException +import kotlinx.coroutines.runBlocking import kotlinx.coroutines.tasks.await import kotlinx.coroutines.test.runTest import kotlinx.serialization.json.Json @@ -17,6 +20,7 @@ import kotlinx.serialization.json.jsonPrimitive import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse import org.junit.Assert.assertNull +import org.junit.Assert.assertThrows import org.junit.Assert.assertTrue import org.junit.Before import org.junit.Test @@ -91,6 +95,7 @@ class FirebaseAuthEmailFlowsTest : FirebaseTest() { user.sendEmailVerification().await() val code = latestCode("VERIFY_EMAIL")["oobCode"]!!.jsonPrimitive.content assertEquals(ActionCodeResult.VERIFY_EMAIL, auth.checkActionCode(code).await().operation) + assertThrows(FirebaseAuthActionCodeException::class.java) { runBlocking { auth.verifyPasswordResetCode(code).await() } } auth.applyActionCode(code).await() assertTrue(lookupEmailVerified(user.getIdToken(false).await().token!!)) } @@ -104,6 +109,10 @@ class FirebaseAuthEmailFlowsTest : FirebaseTest() { assertEquals(email, linked.user!!.email) assertFalse(linked.user!!.isAnonymous) + val relink = assertThrows(FirebaseAuthUserCollisionException::class.java) { + runBlocking { linked.user!!.linkWithCredential(EmailAuthProvider.getCredential(email, "another")).await() } + } + assertEquals("ERROR_PROVIDER_ALREADY_LINKED", relink.errorCode) auth.signOut() val signedIn = auth.signInWithCredential(EmailAuthProvider.getCredential(email, "linkpass1")).await() assertEquals(anonymous.uid, signedIn.user!!.uid) From 4538b49381dd7a758fb1354da5c5797e96e0b32a Mon Sep 17 00:00:00 2001 From: Nick Williams Date: Sat, 31 Oct 2026 04:53:27 +0000 Subject: [PATCH 3/4] Run the CI emulator as the tests' project The tests initialise their app as fir-java-sdk while the emulator ran as my-firebase-project, which it warned about on every request. The ID tokens it issued carried its own project as audience, so updateCurrentUser's project check rejected them, and the action codes it recorded were listed under its own project, so the email-flow tests found none. The emulator now runs as the tests' project, as it does locally. --- .github/workflows/build-pr.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/build-pr.yml b/.github/workflows/build-pr.yml index 028ce50..078bca6 100644 --- a/.github/workflows/build-pr.yml +++ b/.github/workflows/build-pr.yml @@ -18,4 +18,4 @@ jobs: - name: Install Firebase CLI run: npm install -g firebase-tools - name: Build - run: firebase emulators:exec --project my-firebase-project --import=src/test/resources/firebase_data './gradlew build' + run: firebase emulators:exec --project fir-java-sdk --import=src/test/resources/firebase_data './gradlew build' From 7d16df22a47d8732a2bda0cc8dc136e0830134db Mon Sep 17 00:00:00 2001 From: Nick Williams Date: Sat, 31 Oct 2026 05:23:40 +0000 Subject: [PATCH 4/4] Address the second review of the Auth API alignment reload refreshes the profile after the token, so a verified or changed email shows on the current user, and the account lookup also refreshes the phone number, verification state and providers. Linking refreshes the user's ID token first, as the other user actions do, which a token that is not a JWT (a test double's) now survives. Invalid and expired action codes arrive as FirebaseAuthActionCodeException and a weak password as FirebaseAuthWeakPasswordException with the server's reason, keeping the server's codes. An action link needs its apiKey to parse, as on Android, a reverted second factor reports the factor through ActionCodeMultiFactorInfo, and the username falls back to the provider profile's login or screen_name. ActionCodeSettings and the exception details are Kotlin properties behind the Android getter names, so Kotlin written for Android reads them the same way. Setting a tenant throws, since the port signs in to the default tenant only. The emulator's debug log left in the tree is removed and ignored. --- .gitignore | 1 + README.md | 2 +- firebase-debug.log | 50 --------- .../firebase/auth/ActionCodeResultImpl.kt | 23 ++++ .../firebase/auth/ActionCodeSettings.kt | 68 +++++------- .../com/google/firebase/auth/ActionCodeUrl.kt | 5 +- .../google/firebase/auth/AuthResultImpl.kt | 3 +- .../com/google/firebase/auth/FirebaseAuth.kt | 104 +++++++++++------- .../auth/FirebaseAuthMultiFactorException.kt | 6 +- .../FirebaseAuthUserCollisionException.kt | 9 +- .../auth/FirebaseAuthWeakPasswordException.kt | 6 +- src/test/kotlin/FirebaseAuthApiTest.kt | 38 +++---- src/test/kotlin/FirebaseAuthEmailFlowsTest.kt | 28 ++--- 13 files changed, 161 insertions(+), 182 deletions(-) delete mode 100644 firebase-debug.log diff --git a/.gitignore b/.gitignore index 82c5134..cb13fd3 100644 --- a/.gitignore +++ b/.gitignore @@ -6,3 +6,4 @@ build/ /local.properties /.DS_Store +/firebase-debug.log diff --git a/README.md b/README.md index 829ad13..1a83461 100644 --- a/README.md +++ b/README.md @@ -148,7 +148,7 @@ the auth state and ID token listeners. Not supported, as they need a device or a browser: phone number verification (`PhoneAuthProvider.verifyPhoneNumber` reports a failure to its callbacks), multi-factor enrolment and sign-in, provider sign-in through an Activity -(`startActivityForSignInWithProvider` and the `FirebaseUser` counterparts fail) and reCAPTCHA. Not yet implemented: +(`startActivityForSignInWithProvider` and the `FirebaseUser` counterparts fail), reCAPTCHA and multi-tenancy (`setTenantId` throws). Not yet implemented: `reauthenticate`, `reauthenticateAndRetrieveData`, `unlink` and `updatePassword`. #### Realtime Database does not support [Disk Persistence](https://firebase.google.com/docs/database/android/offline-capabilities), and should be setup as follows: ```java diff --git a/firebase-debug.log b/firebase-debug.log deleted file mode 100644 index 216ed43..0000000 --- a/firebase-debug.log +++ /dev/null @@ -1,50 +0,0 @@ -[debug] [2026-10-31T04:31:58.246Z] ---------------------------------------------------------------------- -[debug] [2026-10-31T04:31:58.248Z] Command: /opt/node22/bin/node /opt/node22/bin/firebase emulators:start --project fir-java-sdk --import=src/test/resources/firebase_data -[debug] [2026-10-31T04:31:58.248Z] CLI Version: 14.27.0 -[debug] [2026-10-31T04:31:58.249Z] Platform: linux -[debug] [2026-10-31T04:31:58.249Z] Node Version: v22.22.2 -[debug] [2026-10-31T04:31:58.249Z] Time: Sat Oct 31 2026 04:31:58 GMT+0000 (Coordinated Universal Time) -[debug] [2026-10-31T04:31:58.249Z] ---------------------------------------------------------------------- -[debug] -[debug] [2026-10-31T04:31:58.462Z] > command requires scopes: ["email","openid","https://www.googleapis.com/auth/cloudplatformprojects.readonly","https://www.googleapis.com/auth/firebase","https://www.googleapis.com/auth/cloud-platform"] -[debug] Failed to authenticate, have you run firebase login? -[warn] ⚠ emulators: You are not currently authenticated so some features may not work correctly. Please run firebase login to authenticate the CLI. -[info] i emulators: Starting emulators: auth {"metadata":{"emulator":{"name":"hub"},"message":"Starting emulators: auth"}} -[warn] ⚠ hub: Error when trying to check port 4400 on ::1: Error: listen EAFNOSUPPORT: address family not supported ::1:4400 {"metadata":{"emulator":{"name":"hub"},"message":"Error when trying to check port 4400 on ::1: Error: listen EAFNOSUPPORT: address family not supported ::1:4400"}} -[warn] ⚠ hub: Port 4400 is available on 127.0.0.1 but not ::1. This may cause issues with some clients. {"metadata":{"emulator":{"name":"hub"},"message":"Port 4400 is available on 127.0.0.1 but not ::1. This may cause issues with some clients."}} -[warn] ⚠ hub: If you encounter connectivity issues, consider switching to a different port or explicitly specifying "host": "" instead of hostname in firebase.json {"metadata":{"emulator":{"name":"hub"},"message":"If you encounter connectivity issues, consider switching to a different port or explicitly specifying \"host\": \"\" instead of hostname in firebase.json"}} -[warn] ⚠ ui: Error when trying to check port 4000 on ::1: Error: listen EAFNOSUPPORT: address family not supported ::1:4000 {"metadata":{"emulator":{"name":"ui"},"message":"Error when trying to check port 4000 on ::1: Error: listen EAFNOSUPPORT: address family not supported ::1:4000"}} -[warn] ⚠ ui: Port 4000 is available on 127.0.0.1 but not ::1. This may cause issues with some clients. {"metadata":{"emulator":{"name":"ui"},"message":"Port 4000 is available on 127.0.0.1 but not ::1. This may cause issues with some clients."}} -[warn] ⚠ ui: If you encounter connectivity issues, consider switching to a different port or explicitly specifying "host": "" instead of hostname in firebase.json {"metadata":{"emulator":{"name":"ui"},"message":"If you encounter connectivity issues, consider switching to a different port or explicitly specifying \"host\": \"\" instead of hostname in firebase.json"}} -[warn] ⚠ logging: Error when trying to check port 4500 on ::1: Error: listen EAFNOSUPPORT: address family not supported ::1:4500 {"metadata":{"emulator":{"name":"logging"},"message":"Error when trying to check port 4500 on ::1: Error: listen EAFNOSUPPORT: address family not supported ::1:4500"}} -[warn] ⚠ logging: Port 4500 is available on 127.0.0.1 but not ::1. This may cause issues with some clients. {"metadata":{"emulator":{"name":"logging"},"message":"Port 4500 is available on 127.0.0.1 but not ::1. This may cause issues with some clients."}} -[warn] ⚠ logging: If you encounter connectivity issues, consider switching to a different port or explicitly specifying "host": "" instead of hostname in firebase.json {"metadata":{"emulator":{"name":"logging"},"message":"If you encounter connectivity issues, consider switching to a different port or explicitly specifying \"host\": \"\" instead of hostname in firebase.json"}} -[warn] ⚠ auth: Error when trying to check port 9099 on ::1: Error: listen EAFNOSUPPORT: address family not supported ::1:9099 {"metadata":{"emulator":{"name":"auth"},"message":"Error when trying to check port 9099 on ::1: Error: listen EAFNOSUPPORT: address family not supported ::1:9099"}} -[warn] ⚠ auth: Port 9099 is available on 127.0.0.1 but not ::1. This may cause issues with some clients. {"metadata":{"emulator":{"name":"auth"},"message":"Port 9099 is available on 127.0.0.1 but not ::1. This may cause issues with some clients."}} -[warn] ⚠ auth: If you encounter connectivity issues, consider switching to a different port or explicitly specifying "host": "" instead of hostname in firebase.json {"metadata":{"emulator":{"name":"auth"},"message":"If you encounter connectivity issues, consider switching to a different port or explicitly specifying \"host\": \"\" instead of hostname in firebase.json"}} -[debug] [2026-10-31T04:32:01.556Z] assigned listening specs for emulators {"user":{"hub":[{"address":"127.0.0.1","family":"IPv4","port":4400}],"ui":[{"address":"127.0.0.1","family":"IPv4","port":4000}],"logging":[{"address":"127.0.0.1","family":"IPv4","port":4500}],"auth":[{"address":"127.0.0.1","family":"IPv4","port":9099}]},"metadata":{"message":"assigned listening specs for emulators"}} -[debug] [2026-10-31T04:32:01.559Z] Emulator locator file path: /tmp/hub-fir-java-sdk.json -[debug] [2026-10-31T04:32:01.560Z] [hub] writing locator at /tmp/hub-fir-java-sdk.json -[info] i auth: Importing config from /home/user/firebase-java-sdk/src/test/resources/firebase_data/auth_export/config.json {"metadata":{"emulator":{"name":"auth"},"message":"Importing config from /home/user/firebase-java-sdk/src/test/resources/firebase_data/auth_export/config.json"}} -[info] i auth: Importing accounts from /home/user/firebase-java-sdk/src/test/resources/firebase_data/auth_export/accounts.json {"metadata":{"emulator":{"name":"auth"},"message":"Importing accounts from /home/user/firebase-java-sdk/src/test/resources/firebase_data/auth_export/accounts.json"}} -[debug] [2026-10-31T04:32:07.953Z] Could not find VSCode notification endpoint: FetchError: request to http://localhost:40001/vscode/notify failed, reason: connect ECONNREFUSED 127.0.0.1:40001. If you are not running the Firebase Data Connect VSCode extension, this is expected and not an issue. -[info] -┌─────────────────────────────────────────────────────────────┐ -│ ✔ All emulators ready! It is now safe to connect your app. │ -│ i View Emulator UI at http://127.0.0.1:4000/ │ -└─────────────────────────────────────────────────────────────┘ - -┌────────────────┬────────────────┬────────────────────────────┐ -│ Emulator │ Host:Port │ View in Emulator UI │ -├────────────────┼────────────────┼────────────────────────────┤ -│ Authentication │ 127.0.0.1:9099 │ http://127.0.0.1:4000/auth │ -└────────────────┴────────────────┴────────────────────────────┘ - Emulator Hub host: 127.0.0.1 port: 4400 - Other reserved ports: 4500 - -Issues? Report them at https://github.com/firebase/firebase-tools/issues and attach the *-debug.log files. - -[info] i To reset the password for flows11268416-7f81-477e-a8d3-59e618ae08fb@example.com, follow this link: http://127.0.0.1:9099/emulator/action?mode=resetPassword&lang=en&oobCode=SXo-vbmm9JyHujIjtU3vgBE6KW52ecIgQYqpCUM55KktK_I9hq2AL8&apiKey=fake-api-key&newPassword=NEW_PASSWORD_HERE {"metadata":{"emulator":{"name":"auth"},"message":"To reset the password for flows11268416-7f81-477e-a8d3-59e618ae08fb@example.com, follow this link: http://127.0.0.1:9099/emulator/action?mode=resetPassword&lang=en&oobCode=SXo-vbmm9JyHujIjtU3vgBE6KW52ecIgQYqpCUM55KktK_I9hq2AL8&apiKey=fake-api-key&newPassword=NEW_PASSWORD_HERE"}} -[warn] ⚠ canHandleCodeInApp is unsupported in Auth Emulator. All OOB operations will complete via web. {"metadata":{"emulator":{"name":"auth"},"message":"canHandleCodeInApp is unsupported in Auth Emulator. All OOB operations will complete via web."}} -[info] i To sign in as flowsebf01040-fbab-427e-adcc-64a3a463a02b@example.com, follow this link: http://127.0.0.1:9099/emulator/action?mode=signIn&lang=en&oobCode=BE4aKRNHuyQBp35NeQZHuXxUHszv08tZPjiYgG1ks1dg6CyE0dPHkw&apiKey=fake-api-key&continueUrl=https%3A%2F%2Fexample.com%2Ffinish {"metadata":{"emulator":{"name":"auth"},"message":"To sign in as flowsebf01040-fbab-427e-adcc-64a3a463a02b@example.com, follow this link: http://127.0.0.1:9099/emulator/action?mode=signIn&lang=en&oobCode=BE4aKRNHuyQBp35NeQZHuXxUHszv08tZPjiYgG1ks1dg6CyE0dPHkw&apiKey=fake-api-key&continueUrl=https%3A%2F%2Fexample.com%2Ffinish"}} -[info] i To verify the email address flows2ffd184d-1380-4bf9-8fb1-2295e23573c7@example.com, follow this link: http://127.0.0.1:9099/emulator/action?mode=verifyEmail&lang=en&oobCode=KGaKIl2dWWe64lQRsiTjebIP28bMIoHAuSduQje7Y65dw2GsyRLfOz&apiKey=fake-api-key {"metadata":{"emulator":{"name":"auth"},"message":"To verify the email address flows2ffd184d-1380-4bf9-8fb1-2295e23573c7@example.com, follow this link: http://127.0.0.1:9099/emulator/action?mode=verifyEmail&lang=en&oobCode=KGaKIl2dWWe64lQRsiTjebIP28bMIoHAuSduQje7Y65dw2GsyRLfOz&apiKey=fake-api-key"}} diff --git a/src/main/java/com/google/firebase/auth/ActionCodeResultImpl.kt b/src/main/java/com/google/firebase/auth/ActionCodeResultImpl.kt index be0cb72..df2008f 100644 --- a/src/main/java/com/google/firebase/auth/ActionCodeResultImpl.kt +++ b/src/main/java/com/google/firebase/auth/ActionCodeResultImpl.kt @@ -2,7 +2,9 @@ package com.google.firebase.auth import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.contentOrNull +import kotlinx.serialization.json.jsonObject import kotlinx.serialization.json.jsonPrimitive +import java.time.Instant /** The result of `accounts:resetPassword` called with a code alone: its `requestType` and the account it concerns. */ internal class ActionCodeResultImpl(data: JsonObject) : ActionCodeResult { @@ -25,6 +27,7 @@ internal class ActionCodeResultImpl(data: JsonObject) : ActionCodeResult { // Recovering restores `email`; the address being left is `newEmail`. ActionCodeResult.RECOVER_EMAIL -> EmailInfo(email, newEmail) ActionCodeResult.VERIFY_BEFORE_CHANGE_EMAIL -> EmailInfo(newEmail, email) + ActionCodeResult.REVERT_SECOND_FACTOR_ADDITION -> data["mfaInfo"]?.jsonObject?.let { MultiFactorEmailInfo(email, multiFactorInfoOf(it)) } ActionCodeResult.ERROR -> null else -> email?.let { ActionCodeInfo(it) } } @@ -44,4 +47,24 @@ internal class ActionCodeResultImpl(data: JsonObject) : ActionCodeResult { private class EmailInfo(email: String?, private val previousEmail: String?) : ActionCodeEmailInfo(email) { override fun getPreviousEmail(): String? = previousEmail } + + private class MultiFactorEmailInfo(email: String?, private val multiFactorInfo: MultiFactorInfo) : ActionCodeMultiFactorInfo() { + init { + this.email = email + } + + override fun getMultiFactorInfo(): MultiFactorInfo = multiFactorInfo + } + + private companion object { + /** The factor a `mfaInfo` object describes: a phone factor when it carries a number, a TOTP factor otherwise. */ + fun multiFactorInfoOf(info: JsonObject): MultiFactorInfo { + val uid = info["mfaEnrollmentId"]?.jsonPrimitive?.contentOrNull.orEmpty() + val displayName = info["displayName"]?.jsonPrimitive?.contentOrNull + val enrolledAt = + info["enrolledAt"]?.jsonPrimitive?.contentOrNull?.let { runCatching { Instant.parse(it).toEpochMilli() }.getOrNull() } ?: 0L + val phoneNumber = info["phoneInfo"]?.jsonPrimitive?.contentOrNull + return if (phoneNumber != null) PhoneMultiFactorInfo(uid, displayName, enrolledAt, phoneNumber) else TotpMultiFactorInfo(uid, displayName, enrolledAt) + } + } } diff --git a/src/main/java/com/google/firebase/auth/ActionCodeSettings.kt b/src/main/java/com/google/firebase/auth/ActionCodeSettings.kt index e65183a..e582df8 100644 --- a/src/main/java/com/google/firebase/auth/ActionCodeSettings.kt +++ b/src/main/java/com/google/firebase/auth/ActionCodeSettings.kt @@ -8,35 +8,23 @@ import kotlinx.serialization.json.JsonPrimitive * `sendOobCode` as its continue URL, bundle ids and link domain. */ class ActionCodeSettings private constructor( - private val url: String, - private val iOSBundleId: String?, - private val androidPackageName: String?, - private val androidInstallApp: Boolean, - private val androidMinimumVersion: String?, + val url: String, + val iOSBundle: String?, + val androidPackageName: String?, + val androidInstallApp: Boolean, + val androidMinimumVersion: String?, private val handleCodeInApp: Boolean, - private val linkDomain: String?, + val linkDomain: String?, private val dynamicLinkDomain: String? ) { - fun getUrl(): String = url - - fun getIOSBundle(): String? = iOSBundleId - - fun getAndroidPackageName(): String? = androidPackageName - - fun getAndroidInstallApp(): Boolean = androidInstallApp - - fun getAndroidMinimumVersion(): String? = androidMinimumVersion - fun canHandleCodeInApp(): Boolean = handleCodeInApp - fun getLinkDomain(): String? = linkDomain - /** The `sendOobCode` request fields these settings add. */ internal fun toRequestFields(): Map = buildMap { put("continueUrl", JsonPrimitive(url)) put("canHandleCodeInApp", JsonPrimitive(handleCodeInApp)) - iOSBundleId?.let { put("iOSBundleId", JsonPrimitive(it)) } + iOSBundle?.let { put("iOSBundleId", JsonPrimitive(it)) } androidPackageName?.let { put("androidPackageName", JsonPrimitive(it)) put("androidInstallApp", JsonPrimitive(androidInstallApp)) @@ -47,22 +35,29 @@ class ActionCodeSettings private constructor( } class Builder internal constructor() { - private var url: String? = null - private var iOSBundleId: String? = null + private var urlValue: String? = null + private var iOSBundleIdValue: String? = null private var androidPackageName: String? = null private var androidInstallApp: Boolean = false private var androidMinimumVersion: String? = null - private var handleCodeInApp: Boolean = false - private var linkDomain: String? = null - private var dynamicLinkDomain: String? = null + private var handleCodeInAppValue: Boolean = false + private var linkDomainValue: String? = null + private var dynamicLinkDomainValue: String? = null - fun setUrl(url: String): Builder = apply { this.url = url } + val url: String? get() = urlValue - fun getUrl(): String? = url + val iOSBundleId: String? get() = iOSBundleIdValue - fun setIOSBundleId(iOSBundleId: String): Builder = apply { this.iOSBundleId = iOSBundleId } + val handleCodeInApp: Boolean get() = handleCodeInAppValue - fun getIOSBundleId(): String? = iOSBundleId + val linkDomain: String? get() = linkDomainValue + + @Deprecated("Use linkDomain") + val dynamicLinkDomain: String? get() = dynamicLinkDomainValue + + fun setUrl(url: String): Builder = apply { urlValue = url } + + fun setIOSBundleId(iOSBundleId: String): Builder = apply { iOSBundleIdValue = iOSBundleId } fun setAndroidPackageName(androidPackageName: String, installIfNotAvailable: Boolean, minimumVersion: String?): Builder = apply { this.androidPackageName = androidPackageName @@ -70,24 +65,17 @@ class ActionCodeSettings private constructor( this.androidMinimumVersion = minimumVersion } - fun setHandleCodeInApp(canHandleCodeInApp: Boolean): Builder = apply { this.handleCodeInApp = canHandleCodeInApp } + fun setHandleCodeInApp(canHandleCodeInApp: Boolean): Builder = apply { handleCodeInAppValue = canHandleCodeInApp } - fun getHandleCodeInApp(): Boolean = handleCodeInApp - - fun setLinkDomain(linkDomain: String): Builder = apply { this.linkDomain = linkDomain } - - fun getLinkDomain(): String? = linkDomain + fun setLinkDomain(linkDomain: String): Builder = apply { linkDomainValue = linkDomain } @Deprecated("Use setLinkDomain") - fun setDynamicLinkDomain(dynamicLinkDomain: String): Builder = apply { this.dynamicLinkDomain = dynamicLinkDomain } - - @Deprecated("Use getLinkDomain") - fun getDynamicLinkDomain(): String? = dynamicLinkDomain + fun setDynamicLinkDomain(dynamicLinkDomain: String): Builder = apply { dynamicLinkDomainValue = dynamicLinkDomain } fun build(): ActionCodeSettings { - val url = requireNotNull(url) { "ActionCodeSettings url must be set" } + val url = requireNotNull(urlValue) { "ActionCodeSettings url must be set" } require(url.isNotBlank()) { "ActionCodeSettings url must not be blank" } - return ActionCodeSettings(url, iOSBundleId, androidPackageName, androidInstallApp, androidMinimumVersion, handleCodeInApp, linkDomain, dynamicLinkDomain) + return ActionCodeSettings(url, iOSBundleIdValue, androidPackageName, androidInstallApp, androidMinimumVersion, handleCodeInAppValue, linkDomainValue, dynamicLinkDomainValue) } } diff --git a/src/main/java/com/google/firebase/auth/ActionCodeUrl.kt b/src/main/java/com/google/firebase/auth/ActionCodeUrl.kt index ec35fcd..4833ba0 100644 --- a/src/main/java/com/google/firebase/auth/ActionCodeUrl.kt +++ b/src/main/java/com/google/firebase/auth/ActionCodeUrl.kt @@ -13,16 +13,17 @@ class ActionCodeUrl private constructor( val operation: Int ) { companion object { - /** The action link's parts, or null when [link] is not a URL with an `oobCode` and a `mode`. */ + /** The action link's parts, or null when [link] is not a URL with an `apiKey`, an `oobCode` and a `mode`, as on Android. */ @JvmStatic fun parseLink(link: String): ActionCodeUrl? { val uri = runCatching { URI(link.trim()) }.getOrNull() ?: return null val params = queryParameters(uri.rawQuery) params["link"]?.let { return parseLink(it) } params["deep_link_id"]?.let { return parseLink(it) } + val apiKey = params["apiKey"] ?: return null val code = params["oobCode"] ?: return null val mode = params["mode"] ?: return null - return ActionCodeUrl(params["apiKey"], code, params["continueUrl"], params["lang"], operationOf(mode)) + return ActionCodeUrl(apiKey, code, params["continueUrl"], params["lang"], operationOf(mode)) } private fun queryParameters(rawQuery: String?): Map = diff --git a/src/main/java/com/google/firebase/auth/AuthResultImpl.kt b/src/main/java/com/google/firebase/auth/AuthResultImpl.kt index 2cc5d71..0b1d8e4 100644 --- a/src/main/java/com/google/firebase/auth/AuthResultImpl.kt +++ b/src/main/java/com/google/firebase/auth/AuthResultImpl.kt @@ -52,7 +52,8 @@ internal class AdditionalUserInfoImpl( return AdditionalUserInfoImpl( providerId = data["providerId"]?.jsonPrimitive?.contentOrNull, profile = profile, - username = data["screenName"]?.jsonPrimitive?.contentOrNull, + // GitHub's profile carries the username as login, Twitter's as screen_name. + username = data["screenName"]?.jsonPrimitive?.contentOrNull ?: (profile["login"] ?: profile["screen_name"]) as? String, newUser = data["isNewUser"]?.jsonPrimitive?.booleanOrNull ?: newUserByDefault ) } diff --git a/src/main/java/com/google/firebase/auth/FirebaseAuth.kt b/src/main/java/com/google/firebase/auth/FirebaseAuth.kt index 58af8a0..5e09d3e 100644 --- a/src/main/java/com/google/firebase/auth/FirebaseAuth.kt +++ b/src/main/java/com/google/firebase/auth/FirebaseAuth.kt @@ -123,12 +123,15 @@ data class FirebaseUserImpl internal constructor( override val providerId: String get() = FirebaseAuthProvider.PROVIDER_ID + /** The ID token's claims; empty when the token is not a JWT, as a test double's may not be. */ val claims: Map by lazy { - jsonParser - .parseToJsonElement(String(Base64.getUrlDecoder().decode(idToken.split(".")[1]))) - .jsonObject - .run { value as? Map? } - .orEmpty() + runCatching { + jsonParser + .parseToJsonElement(String(Base64.getUrlDecoder().decode(idToken.split(".")[1]))) + .jsonObject + .run { value as? Map? } + .orEmpty() + }.getOrDefault(emptyMap()) } internal val JsonElement.value get(): Any? = @@ -183,10 +186,12 @@ data class FirebaseUserImpl internal constructor( override fun updateEmail(email: String): Task = FirebaseAuth.getInstance(app).updateEmail(email) + /** Refreshes the token, then the profile, so a verified or changed email is visible on the current user. */ override fun reload(): Task { - val source = TaskCompletionSource() - FirebaseAuth.getInstance(app).refreshToken(this, source) { null } - return source.task + val source = TaskCompletionSource() + val auth = FirebaseAuth.getInstance(app) + auth.refreshToken(this, source) { it } + return source.task.onSuccessTask { auth.updateByGetAccountInfo().onSuccessTask { Tasks.forResult(null) } } } override fun verifyBeforeUpdateEmail( @@ -412,7 +417,7 @@ class FirebaseAuth constructor( } } - private fun updateByGetAccountInfo(): Task { + internal fun updateByGetAccountInfo(): Task { val source = TaskCompletionSource() val body = @@ -447,12 +452,17 @@ class FirebaseAuth constructor( val data = jsonParser.parseToJsonElement(response.body?.use { it.string() } ?: "").jsonObject val profile = accountProfile(data) val previous = requireNotNull(user) { "No user for account lookup" } + val providerIds = + profile["providerUserInfo"]?.jsonArray?.mapNotNull { it.jsonObject["providerId"]?.jsonPrimitive?.contentOrNull }?.distinct().orEmpty() user = previous.copy( uid = responseUid(data, previous.idToken), createdAt = profile["createdAt"]?.jsonPrimitive?.longOrNull ?: previous.createdAt, email = profile["email"]?.jsonPrimitive?.contentOrNull ?: previous.email, photoUrlString = profile["photoUrl"]?.jsonPrimitive?.contentOrNull ?: previous.photoUrlString, - displayName = profile["displayName"]?.jsonPrimitive?.contentOrNull ?: previous.displayName + displayName = profile["displayName"]?.jsonPrimitive?.contentOrNull ?: previous.displayName, + phoneNumber = profile["phoneNumber"]?.jsonPrimitive?.contentOrNull ?: previous.phoneNumber, + isEmailVerified = profile["emailVerified"]?.jsonPrimitive?.booleanOrNull ?: previous.isEmailVerified, + providerIds = providerIds.ifEmpty { previous.providerIds } ) source.setResult(AuthResultImpl(user, null, null)) } catch (exception: Exception) { @@ -517,9 +527,9 @@ class FirebaseAuth constructor( action: String, request: Request, response: Response - ): FirebaseAuthInvalidUserException { + ): FirebaseAuthException { val body = response.body?.use { it.string() }.orEmpty() - val errorCode = + val serverMessage = runCatching { jsonParser .parseToJsonElement(body) @@ -529,13 +539,17 @@ class FirebaseAuth constructor( ?.jsonPrimitive ?.contentOrNull }.getOrNull() ?: "UNKNOWN_ERROR" - - return FirebaseAuthInvalidUserException( - errorCode, - "$errorCode: $action API returned an error, " + + // The server appends a reason to some codes: "WEAK_PASSWORD : Password should be at least 6 characters". + val errorCode = serverMessage.substringBefore(" :").substringBefore(":") + val message = + "$serverMessage: $action API returned an error, " + "with endpoint [${request.method}] ${request.url.encodedPath} -- " + "response [${response.code}] ${response.message}" - ) + return when (errorCode) { + "INVALID_OOB_CODE", "EXPIRED_OOB_CODE" -> FirebaseAuthActionCodeException(errorCode, message) + "WEAK_PASSWORD" -> FirebaseAuthWeakPasswordException(errorCode, message, serverMessage.substringAfter(':', "").trim().ifEmpty { null }) + else -> FirebaseAuthInvalidUserException(serverMessage, message) + } } fun signOut() { @@ -1011,30 +1025,32 @@ class FirebaseAuth constructor( ) } - return enqueueCredentialAuthPost(authCredential, currentIdToken = signedInUser.idToken) { responseBody -> - val data = jsonParser.parseToJsonElement(responseBody).jsonObject - val linkedUser = - FirebaseUserImpl( - app = app, - data = data, - isAnonymous = false, - email = data["email"]?.jsonPrimitive?.contentOrNull ?: signedInUser.email, - photoUrl = data["photoUrl"]?.jsonPrimitive?.contentOrNull ?: signedInUser.photoUrlString, - displayName = data["displayName"]?.jsonPrimitive?.contentOrNull ?: signedInUser.displayName, - phoneNumber = data["phoneNumber"]?.jsonPrimitive?.contentOrNull ?: signedInUser.phoneNumber, - isEmailVerified = data["emailVerified"]?.jsonPrimitive?.booleanOrNull ?: signedInUser.isEmailVerified, - createdAt = signedInUser.createdAt, - lastSignInAt = signedInUser.lastSignInAt, - existingProviderData = signedInUser.providerData, - urlFactory = urlFactory - ) - if (linkedUser.uid != signedInUser.uid) { - throw FirebaseAuthInvalidUserException( - "ERROR_USER_MISMATCH", - "The linked credential returned a different Firebase user." - ) - } - linkedUser + return freshIdToken(signedInUser).onSuccessTask { idToken -> + enqueueCredentialAuthPost(authCredential, currentIdToken = idToken, setResult = { responseBody -> + val data = jsonParser.parseToJsonElement(responseBody).jsonObject + val linkedUser = + FirebaseUserImpl( + app = app, + data = data, + isAnonymous = false, + email = data["email"]?.jsonPrimitive?.contentOrNull ?: signedInUser.email, + photoUrl = data["photoUrl"]?.jsonPrimitive?.contentOrNull ?: signedInUser.photoUrlString, + displayName = data["displayName"]?.jsonPrimitive?.contentOrNull ?: signedInUser.displayName, + phoneNumber = data["phoneNumber"]?.jsonPrimitive?.contentOrNull ?: signedInUser.phoneNumber, + isEmailVerified = data["emailVerified"]?.jsonPrimitive?.booleanOrNull ?: signedInUser.isEmailVerified, + createdAt = signedInUser.createdAt, + lastSignInAt = signedInUser.lastSignInAt, + existingProviderData = signedInUser.providerData, + urlFactory = urlFactory + ) + if (linkedUser.uid != signedInUser.uid) { + throw FirebaseAuthInvalidUserException( + "ERROR_USER_MISMATCH", + "The linked credential returned a different Firebase user." + ) + } + linkedUser + }) } } @@ -1173,8 +1189,12 @@ class FirebaseAuth constructor( languageCode = Locale.getDefault().toLanguageTag() } - /** The tenant to sign in to; the JVM port always uses the project's default tenant. */ + /** The tenant to sign in to. The JVM port signs in to the project's default tenant only, so a tenant cannot be set. */ var tenantId: String? = null + set(value) { + if (value != null) throw UnsupportedOperationException("Multi-tenancy is not supported by firebase-java-sdk") + field = null + } /** The domain hosting the project's sign-in helpers; the JVM port runs no browser flows, so it is only kept. */ var customAuthDomain: String? = null diff --git a/src/main/java/com/google/firebase/auth/FirebaseAuthMultiFactorException.kt b/src/main/java/com/google/firebase/auth/FirebaseAuthMultiFactorException.kt index 8188070..15cd0a0 100644 --- a/src/main/java/com/google/firebase/auth/FirebaseAuthMultiFactorException.kt +++ b/src/main/java/com/google/firebase/auth/FirebaseAuthMultiFactorException.kt @@ -3,7 +3,5 @@ package com.google.firebase.auth class FirebaseAuthMultiFactorException( errorCode: String, detailMessage: String, - private val resolver: MultiFactorResolver -) : FirebaseAuthException(errorCode, detailMessage) { - fun getResolver(): MultiFactorResolver = resolver -} + val resolver: MultiFactorResolver +) : FirebaseAuthException(errorCode, detailMessage) diff --git a/src/main/java/com/google/firebase/auth/FirebaseAuthUserCollisionException.kt b/src/main/java/com/google/firebase/auth/FirebaseAuthUserCollisionException.kt index 6b299b9..549de7a 100644 --- a/src/main/java/com/google/firebase/auth/FirebaseAuthUserCollisionException.kt +++ b/src/main/java/com/google/firebase/auth/FirebaseAuthUserCollisionException.kt @@ -1,14 +1,13 @@ package com.google.firebase.auth class FirebaseAuthUserCollisionException(errorCode: String, detailMessage: String) : FirebaseAuthException(errorCode, detailMessage) { - private var email: String? = null - private var updatedCredential: AuthCredential? = null - /** The email of the account that already exists, when the server reported it. */ - fun getEmail(): String? = email + var email: String? = null + private set /** The credential the sign-in produced for the existing account, when the server returned one. */ - fun getUpdatedCredential(): AuthCredential? = updatedCredential + var updatedCredential: AuthCredential? = null + private set internal fun withDetails(email: String?, updatedCredential: AuthCredential?): FirebaseAuthUserCollisionException = apply { this.email = email diff --git a/src/main/java/com/google/firebase/auth/FirebaseAuthWeakPasswordException.kt b/src/main/java/com/google/firebase/auth/FirebaseAuthWeakPasswordException.kt index 04751a5..de0c4c7 100644 --- a/src/main/java/com/google/firebase/auth/FirebaseAuthWeakPasswordException.kt +++ b/src/main/java/com/google/firebase/auth/FirebaseAuthWeakPasswordException.kt @@ -3,10 +3,8 @@ package com.google.firebase.auth class FirebaseAuthWeakPasswordException( errorCode: String, detailMessage: String, - private val reason: String? + /** Why the password was rejected, when the server said. */ + val reason: String? ) : FirebaseAuthInvalidCredentialsException(errorCode, detailMessage) { constructor(errorCode: String, detailMessage: String) : this(errorCode, detailMessage, null) - - /** Why the password was rejected, when the server said. */ - fun getReason(): String? = reason } diff --git a/src/test/kotlin/FirebaseAuthApiTest.kt b/src/test/kotlin/FirebaseAuthApiTest.kt index 5ce3214..7b43c9d 100644 --- a/src/test/kotlin/FirebaseAuthApiTest.kt +++ b/src/test/kotlin/FirebaseAuthApiTest.kt @@ -57,18 +57,18 @@ class FirebaseAuthApiTest : FirebaseTest() { .setAndroidPackageName("com.example", true, "12") .setLinkDomain("example.page.link") .build() - assertEquals("https://example.com/finish", settings.getUrl()) + assertEquals("https://example.com/finish", settings.url) assertTrue(settings.canHandleCodeInApp()) - assertEquals("com.example.ios", settings.getIOSBundle()) - assertEquals("com.example", settings.getAndroidPackageName()) - assertTrue(settings.getAndroidInstallApp()) - assertEquals("12", settings.getAndroidMinimumVersion()) - assertEquals("example.page.link", settings.getLinkDomain()) + assertEquals("com.example.ios", settings.iOSBundle) + assertEquals("com.example", settings.androidPackageName) + assertTrue(settings.androidInstallApp) + assertEquals("12", settings.androidMinimumVersion) + assertEquals("example.page.link", settings.linkDomain) val builder = ActionCodeSettings.newBuilder().setUrl("https://example.com") - assertEquals("https://example.com", builder.getUrl()) - assertFalse(builder.getHandleCodeInApp()) - assertNull(builder.getLinkDomain()) + assertEquals("https://example.com", builder.url) + assertFalse(builder.handleCodeInApp) + assertNull(builder.linkDomain) assertThrows(IllegalArgumentException::class.java) { ActionCodeSettings.newBuilder().build() } } @@ -84,12 +84,13 @@ class FirebaseAuthApiTest : FirebaseTest() { assertEquals("https://example.com/finish", url.continueUrl) assertEquals("en", url.languageCode) - val inner = "https://fir-java-sdk.firebaseapp.com/__/auth/action?mode=signIn&oobCode=xyz" + val inner = "https://fir-java-sdk.firebaseapp.com/__/auth/action?mode=signIn&oobCode=xyz&apiKey=key" val wrapped = "https://example.page.link/?link=" + URLEncoder.encode(inner, "UTF-8") assertEquals(ActionCodeResult.SIGN_IN_WITH_EMAIL_LINK, ActionCodeUrl.parseLink(wrapped)!!.operation) assertTrue(auth.isSignInWithEmailLink(wrapped)) assertFalse(auth.isSignInWithEmailLink(link)) assertNull(ActionCodeUrl.parseLink("https://example.com/")) + assertNull(ActionCodeUrl.parseLink("https://x/?mode=signIn&oobCode=xyz")) // no apiKey assertNull(ActionCodeUrl.parseLink("not a url")) } @@ -109,10 +110,10 @@ class FirebaseAuthApiTest : FirebaseTest() { assertEquals("password", email.provider) assertEquals("password", email.signInMethod) assertFalse(email.toString().contains("secret")) - val link = EmailAuthProvider.getCredentialWithLink("a@b.c", "https://x/?mode=signIn&oobCode=code1") + val link = EmailAuthProvider.getCredentialWithLink("a@b.c", "https://x/?mode=signIn&oobCode=code1&apiKey=key") assertEquals("emailLink", link.signInMethod) assertThrows(IllegalArgumentException::class.java) { EmailAuthProvider.getCredentialWithLink("a@b.c", "https://x/") } - assertThrows(IllegalArgumentException::class.java) { EmailAuthProvider.getCredentialWithLink("a@b.c", "https://x/?mode=resetPassword&oobCode=code1") } + assertThrows(IllegalArgumentException::class.java) { EmailAuthProvider.getCredentialWithLink("a@b.c", "https://x/?mode=resetPassword&oobCode=code1&apiKey=key") } assertTrue(FacebookAuthProvider.getCredential("token") is FacebookAuthCredential) assertEquals("github.com", GithubAuthProvider.getCredential("token").provider) @@ -163,9 +164,8 @@ class FirebaseAuthApiTest : FirebaseTest() { assertEquals(Locale.getDefault().toLanguageTag(), auth.languageCode) auth.languageCode = null - auth.tenantId = "tenant" - assertEquals("tenant", auth.tenantId) - auth.tenantId = null + assertThrows(UnsupportedOperationException::class.java) { auth.tenantId = "tenant" } + assertNull(auth.tenantId) auth.customAuthDomain = "auth.example.com" assertEquals("auth.example.com", auth.customAuthDomain) @@ -178,10 +178,10 @@ class FirebaseAuthApiTest : FirebaseTest() { @Test fun `exceptions carry the android details`() { val collision = FirebaseAuthUserCollisionException("ERROR_EMAIL_ALREADY_IN_USE", "exists") - assertNull(collision.getEmail()) - assertNull(collision.getUpdatedCredential()) - assertEquals("too short", FirebaseAuthWeakPasswordException("ERROR_WEAK_PASSWORD", "weak", "too short").getReason()) - assertNull(FirebaseAuthWeakPasswordException("ERROR_WEAK_PASSWORD", "weak").getReason()) + assertNull(collision.email) + assertNull(collision.updatedCredential) + assertEquals("too short", FirebaseAuthWeakPasswordException("ERROR_WEAK_PASSWORD", "weak", "too short").reason) + assertNull(FirebaseAuthWeakPasswordException("ERROR_WEAK_PASSWORD", "weak").reason) assertEquals("ERROR_MISSING_ACTIVITY", FirebaseAuthMissingActivityForRecaptchaException().errorCode) } diff --git a/src/test/kotlin/FirebaseAuthEmailFlowsTest.kt b/src/test/kotlin/FirebaseAuthEmailFlowsTest.kt index 7de129c..b1b2d71 100644 --- a/src/test/kotlin/FirebaseAuthEmailFlowsTest.kt +++ b/src/test/kotlin/FirebaseAuthEmailFlowsTest.kt @@ -7,24 +7,23 @@ import com.google.firebase.auth.EmailAuthProvider import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.FirebaseAuthActionCodeException import com.google.firebase.auth.FirebaseAuthUserCollisionException +import com.google.firebase.auth.FirebaseAuthWeakPasswordException import kotlinx.coroutines.runBlocking import kotlinx.coroutines.tasks.await import kotlinx.coroutines.test.runTest import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonObject -import kotlinx.serialization.json.JsonPrimitive -import kotlinx.serialization.json.booleanOrNull import kotlinx.serialization.json.jsonArray import kotlinx.serialization.json.jsonObject import kotlinx.serialization.json.jsonPrimitive import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull import org.junit.Assert.assertNull import org.junit.Assert.assertThrows import org.junit.Assert.assertTrue import org.junit.Before import org.junit.Test -import java.net.HttpURLConnection import java.net.URL import java.util.UUID @@ -46,16 +45,6 @@ class FirebaseAuthEmailFlowsTest : FirebaseTest() { private fun latestCode(requestType: String): JsonObject = oobCodes().last { it["email"]?.jsonPrimitive?.content == email && it["requestType"]?.jsonPrimitive?.content == requestType } - private fun lookupEmailVerified(idToken: String): Boolean { - val connection = URL("$emulator/identitytoolkit.googleapis.com/v1/accounts:lookup?key=${options.apiKey}").openConnection() as HttpURLConnection - connection.requestMethod = "POST" - connection.doOutput = true - connection.setRequestProperty("Content-Type", "application/json") - connection.outputStream.use { it.write(JsonObject(mapOf("idToken" to JsonPrimitive(idToken))).toString().toByteArray()) } - val body = connection.inputStream.use { it.readBytes().decodeToString() } - return Json.parseToJsonElement(body).jsonObject["users"]!!.jsonArray.first().jsonObject["emailVerified"]?.jsonPrimitive?.booleanOrNull ?: false - } - @Test fun `a password reset code is checked, verified and confirmed`() = runTest { @@ -97,7 +86,18 @@ class FirebaseAuthEmailFlowsTest : FirebaseTest() { assertEquals(ActionCodeResult.VERIFY_EMAIL, auth.checkActionCode(code).await().operation) assertThrows(FirebaseAuthActionCodeException::class.java) { runBlocking { auth.verifyPasswordResetCode(code).await() } } auth.applyActionCode(code).await() - assertTrue(lookupEmailVerified(user.getIdToken(false).await().token!!)) + auth.currentUser!!.reload().await() + assertTrue(auth.currentUser!!.isEmailVerified) + } + + @Test + fun `server errors arrive as the android exception types`() = + runTest { + val invalidCode = assertThrows(FirebaseAuthActionCodeException::class.java) { runBlocking { auth.checkActionCode("not-a-code").await() } } + assertEquals("INVALID_OOB_CODE", invalidCode.errorCode) + val weak = assertThrows(FirebaseAuthWeakPasswordException::class.java) { runBlocking { auth.createUserWithEmailAndPassword(email, "123").await() } } + assertEquals("WEAK_PASSWORD", weak.errorCode) + assertNotNull(weak.reason) } @Test