Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/build-pr.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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'
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,4 @@ build/
/local.properties
/.DS_Store

/firebase-debug.log
23 changes: 10 additions & 13 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
13 changes: 10 additions & 3 deletions src/main/java/com/google/firebase/auth/ActionCodeEmailInfo.java
Original file line number Diff line number Diff line change
@@ -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() {
}

}
ActionCodeEmailInfo(String email) {
super(email);
}

public abstract String getPreviousEmail();
}
19 changes: 14 additions & 5 deletions src/main/java/com/google/firebase/auth/ActionCodeInfo.java
Original file line number Diff line number Diff line change
@@ -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();
}
public ActionCodeInfo() {
}

ActionCodeInfo(String email) {
this.email = email;
}

public String getEmail() {
return email;
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
package com.google.firebase.auth;

public interface ActionCodeMultiFactorInfo extends ActionCodeInfo {
MultiFactorInfo getMultiFactorInfo();
}
public abstract class ActionCodeMultiFactorInfo extends ActionCodeInfo {
public ActionCodeMultiFactorInfo() {
}

public abstract MultiFactorInfo getMultiFactorInfo();
}
19 changes: 18 additions & 1 deletion src/main/java/com/google/firebase/auth/ActionCodeResult.java
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -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();
}

/** @deprecated use {@link #getInfo()}. */
@Deprecated
String getData(@ActionDataKey int key);
}
70 changes: 70 additions & 0 deletions src/main/java/com/google/firebase/auth/ActionCodeResultImpl.kt
Original file line number Diff line number Diff line change
@@ -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) }
Comment thread
nbransby marked this conversation as resolved.
Resolved
}

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)
}
}
}
86 changes: 86 additions & 0 deletions src/main/java/com/google/firebase/auth/ActionCodeSettings.kt
Original file line number Diff line number Diff line change
@@ -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<String, JsonElement> =
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()
}
}
52 changes: 52 additions & 0 deletions src/main/java/com/google/firebase/auth/ActionCodeUrl.kt
Original file line number Diff line number Diff line change
@@ -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<String, String> =
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
}
}
}
13 changes: 13 additions & 0 deletions src/main/java/com/google/firebase/auth/AdditionalUserInfo.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package com.google.firebase.auth;

import java.util.Map;

public interface AdditionalUserInfo {
Map<String, Object> getProfile();

String getProviderId();

String getUsername();

boolean isNewUser();
}
Loading
Loading