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' 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 6c8d38d..1a83461 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), 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 FirebaseDatabase.getInstance().setPersistenceEnabled(false) 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..df2008f --- /dev/null +++ b/src/main/java/com/google/firebase/auth/ActionCodeResultImpl.kt @@ -0,0 +1,70 @@ +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 { + 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.REVERT_SECOND_FACTOR_ADDITION -> data["mfaInfo"]?.jsonObject?.let { MultiFactorEmailInfo(email, multiFactorInfoOf(it)) } + 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 + } + + 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 new file mode 100644 index 0000000..e582df8 --- /dev/null +++ b/src/main/java/com/google/firebase/auth/ActionCodeSettings.kt @@ -0,0 +1,86 @@ +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( + val url: String, + val iOSBundle: String?, + val androidPackageName: String?, + val androidInstallApp: Boolean, + val androidMinimumVersion: String?, + private val handleCodeInApp: Boolean, + val linkDomain: String?, + private val dynamicLinkDomain: String? +) { + fun canHandleCodeInApp(): Boolean = handleCodeInApp + + /** The `sendOobCode` request fields these settings add. */ + internal fun toRequestFields(): Map = + buildMap { + put("continueUrl", JsonPrimitive(url)) + put("canHandleCodeInApp", JsonPrimitive(handleCodeInApp)) + iOSBundle?.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 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 handleCodeInAppValue: Boolean = false + private var linkDomainValue: String? = null + private var dynamicLinkDomainValue: String? = null + + val url: String? get() = urlValue + + val iOSBundleId: String? get() = iOSBundleIdValue + + val handleCodeInApp: Boolean get() = handleCodeInAppValue + + 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 + this.androidInstallApp = installIfNotAvailable + this.androidMinimumVersion = minimumVersion + } + + fun setHandleCodeInApp(canHandleCodeInApp: Boolean): Builder = apply { handleCodeInAppValue = canHandleCodeInApp } + + fun setLinkDomain(linkDomain: String): Builder = apply { linkDomainValue = linkDomain } + + @Deprecated("Use setLinkDomain") + fun setDynamicLinkDomain(dynamicLinkDomain: String): Builder = apply { dynamicLinkDomainValue = dynamicLinkDomain } + + fun build(): ActionCodeSettings { + val url = requireNotNull(urlValue) { "ActionCodeSettings url must be set" } + require(url.isNotBlank()) { "ActionCodeSettings url must not be blank" } + return ActionCodeSettings(url, iOSBundleIdValue, androidPackageName, androidInstallApp, androidMinimumVersion, handleCodeInAppValue, linkDomainValue, dynamicLinkDomainValue) + } + } + + 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..4833ba0 --- /dev/null +++ b/src/main/java/com/google/firebase/auth/ActionCodeUrl.kt @@ -0,0 +1,52 @@ +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 `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(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..0b1d8e4 --- /dev/null +++ b/src/main/java/com/google/firebase/auth/AuthResultImpl.kt @@ -0,0 +1,80 @@ +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 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 + + /** 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. */ +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, + // 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 + ) + } + + /** 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..9c34e81 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 || 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" + ); + } + 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..5e09d3e 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,6 +14,7 @@ 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 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,18 +114,24 @@ 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 + /** 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? = @@ -176,65 +186,25 @@ 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) } } } - // TODO implement ActionCodeSettings and pass it to the url 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) - ) - ).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) @@ -243,6 +213,12 @@ 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", this, OobRequestType.VERIFY_EMAIL, emptyMap(), actionCodeSettings) + + override fun updatePhoneNumber(credential: PhoneAuthCredential): Task = + FirebaseAuth.getInstance(app).updatePhoneNumber(this, credential) + fun updateProfile( displayName: String?, photoUrl: String? @@ -340,8 +316,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) { @@ -429,10 +412,12 @@ 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 { + internal fun updateByGetAccountInfo(): Task { val source = TaskCompletionSource() val body = @@ -467,14 +452,19 @@ 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, - photoUrl = profile["photoUrl"]?.jsonPrimitive?.contentOrNull ?: previous.photoUrl, - displayName = profile["displayName"]?.jsonPrimitive?.contentOrNull ?: previous.displayName + photoUrlString = profile["photoUrl"]?.jsonPrimitive?.contentOrNull ?: previous.photoUrlString, + 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(AuthResult { user }) + source.setResult(AuthResultImpl(user, null, null)) } catch (exception: Exception) { source.setException(exception) } @@ -537,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) @@ -549,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() { @@ -647,7 +641,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 +734,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 +812,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 +882,119 @@ 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", null, OobRequestType.PASSWORD_RESET, mapOf("email" to JsonPrimitive(email)), settings) + + /** + * 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 { + 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] + * 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(null) } + fun signInWithCredential(authCredential: AuthCredential): Task = enqueueCredentialAuthPost(authCredential, currentIdToken = null) { responseBody -> FirebaseUserImpl( @@ -911,31 +1017,40 @@ 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 - val linkedUser = - FirebaseUserImpl( - app = app, - data = data, - isAnonymous = false, - email = data["email"]?.jsonPrimitive?.contentOrNull ?: signedInUser.email, - photoUrl = data["photoUrl"]?.jsonPrimitive?.contentOrNull ?: signedInUser.photoUrl, - 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 + }) } } @@ -944,10 +1059,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 +1106,129 @@ 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() + ): Task = + postJson( + "confirmPasswordReset", + "identitytoolkit.googleapis.com/v1/accounts:resetPassword", + JsonObject(mapOf("oobCode" to JsonPrimitive(code), "newPassword" to JsonPrimitive(newPassword))) + ).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 -> + 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")) + } - fun fetchSignInMethodsForEmail(email: String): Task = TODO() + /** 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(null) } + + @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", null, 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)) - fun applyActionCode(code: String): Task = TODO() + /** 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")) + 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(null) + } - val languageCode: String get() = TODO() + /** The language of the emails this instance sends, as the `X-Firebase-Locale` header; null for the project default. */ + var languageCode: String? = null - fun isSignInWithEmailLink(link: String): Boolean = TODO() + /** Sets [languageCode] to the JVM's default locale. */ + fun useAppLanguage() { + languageCode = Locale.getDefault().toLanguageTag() + } - fun signInWithEmailLink( - email: String, - link: String - ): Task = TODO() + /** 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 + + 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 current = user + ?: return Tasks.forException(FirebaseNoSignedInUserException("Please sign in before trying to revoke an access token.")) + 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) } + } - 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..15cd0a0 --- /dev/null +++ b/src/main/java/com/google/firebase/auth/FirebaseAuthMultiFactorException.kt @@ -0,0 +1,7 @@ +package com.google.firebase.auth + +class FirebaseAuthMultiFactorException( + errorCode: String, + detailMessage: String, + val resolver: MultiFactorResolver +) : FirebaseAuthException(errorCode, detailMessage) 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..549de7a 100644 --- a/src/main/java/com/google/firebase/auth/FirebaseAuthUserCollisionException.kt +++ b/src/main/java/com/google/firebase/auth/FirebaseAuthUserCollisionException.kt @@ -1,3 +1,16 @@ package com.google.firebase.auth -class FirebaseAuthUserCollisionException(errorCode: String, detailMessage: String) : FirebaseAuthException(errorCode, detailMessage) +class FirebaseAuthUserCollisionException(errorCode: String, detailMessage: String) : FirebaseAuthException(errorCode, detailMessage) { + /** The email of the account that already exists, when the server reported it. */ + var email: String? = null + private set + + /** The credential the sign-in produced for the existing account, when the server returned one. */ + var updatedCredential: AuthCredential? = null + private set + + 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..de0c4c7 100644 --- a/src/main/java/com/google/firebase/auth/FirebaseAuthWeakPasswordException.kt +++ b/src/main/java/com/google/firebase/auth/FirebaseAuthWeakPasswordException.kt @@ -1,3 +1,10 @@ package com.google.firebase.auth -class FirebaseAuthWeakPasswordException(errorCode: String, detailMessage: String) : FirebaseAuthInvalidCredentialsException(errorCode, detailMessage) +class FirebaseAuthWeakPasswordException( + errorCode: String, + detailMessage: 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) +} diff --git a/src/main/java/com/google/firebase/auth/FirebaseUser.kt b/src/main/java/com/google/firebase/auth/FirebaseUser.kt index 2e8b49c..5b7a6a0 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..7b43c9d --- /dev/null +++ b/src/test/kotlin/FirebaseAuthApiTest.kt @@ -0,0 +1,219 @@ +/* + * 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.url) + assertTrue(settings.canHandleCodeInApp()) + 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.url) + assertFalse(builder.handleCodeInApp) + assertNull(builder.linkDomain) + 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&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")) + } + + @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&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&apiKey=key") } + + 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 + + assertThrows(UnsupportedOperationException::class.java) { auth.tenantId = "tenant" } + assertNull(auth.tenantId) + 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.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) + } + + @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..b1b2d71 --- /dev/null +++ b/src/test/kotlin/FirebaseAuthEmailFlowsTest.kt @@ -0,0 +1,133 @@ +/* + * 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 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.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.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 } + + @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) + assertThrows(FirebaseAuthActionCodeException::class.java) { runBlocking { auth.verifyPasswordResetCode(code).await() } } + auth.applyActionCode(code).await() + 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 + 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) + + 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) + 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