Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Respond 401 if there is an error with the firebase token #1089

Merged
merged 1 commit into from
Apr 15, 2024
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
63 changes: 52 additions & 11 deletions service/src/commonMain/kotlin/androidmakers/service/Main.kt
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,13 @@ import io.ktor.server.netty.*
import io.ktor.server.plugins.cors.routing.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import io.ktor.server.util.*
import io.ktor.util.pipeline.*
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.serialization.json.*
import kotlin.time.Duration.Companion.minutes

fun main(@Suppress("UNUSED_PARAMETER") args: Array<String>) {
Expand Down Expand Up @@ -60,6 +62,9 @@ fun main(@Suppress("UNUSED_PARAMETER") args: Array<String>) {
get("/graphql") {
apolloCall(executableSchema)
}
get(Regex("/sandbox/?")) {
call.respondRedirect(call.url { path("/sandbox/index.html") })
}
get("/sandbox/index.html") {
call.respondText(sandboxIndex, ContentType.parse("text/html"))
}
Expand All @@ -71,8 +76,44 @@ fun main(@Suppress("UNUSED_PARAMETER") args: Array<String>) {
val datastore = DatastoreOptions.newBuilder()
.setCredentials(GoogleCredentials.getApplicationDefault()).build().service

private fun Any?.toJsonString(): String {
return this.toJsonElement().toString()
}

private fun Any?.toJsonElement(): JsonElement {
return when (this) {
null -> JsonNull
is String -> JsonPrimitive(this)
is Number -> JsonPrimitive(this)
is Boolean -> JsonPrimitive(this)
is List<*> -> JsonArray(map { it.toJsonElement() })
is Map<*, *> -> JsonObject(map { it.key as String to it.value.toJsonElement() }.toMap())
else -> error("Cannot serialize '$this' to JSON")
}
}

private suspend fun PipelineContext<Unit, ApplicationCall>.apolloCall(executableSchema: ExecutableSchema) {
val context = call.context()
val authResult = call.firebaseUid()
var uid: String? =null
when (authResult) {
is FirebaseUidResult.Error -> {
call.respondText(ContentType.parse("application/json"), HttpStatusCode.Unauthorized) {
mapOf("type" to "signout", "firebaseError" to authResult.code).toJsonString()
}
}
FirebaseUidResult.Expired -> {
call.respondText(ContentType.parse("application/json"), HttpStatusCode.Unauthorized) {
mapOf("type" to "refresh").toJsonString()
}
}
is FirebaseUidResult.SignedIn -> {
uid = authResult.uid
}
FirebaseUidResult.SignedOut -> {
uid = null
}
}
val context = call.context(uid)
call.respondGraphQL(executableSchema, context) {
var maxAge = context.maxAge()

Expand All @@ -91,17 +132,17 @@ private suspend fun PipelineContext<Unit, ApplicationCall>.apolloCall(executable

}

private fun ApplicationCall.firebaseUid(): String? {
return try {
request.headers.get("authorization")
?.substring("Bearer ".length)
?.firebaseUid()
} catch (e: Exception) {
e.printStackTrace()
throw e
private fun ApplicationCall.firebaseUid(): FirebaseUidResult {
val idToken = request.headers.get("authorization")
?.substring("Bearer ".length)

if (idToken == null) {
return FirebaseUidResult.SignedOut
}

return idToken.firebaseUid()
}

private fun ApplicationCall.context(): ExecutionContext {
return AuthenticationContext(firebaseUid()) + DatastoreContext(datastore) + CacheControlContext()
private fun ApplicationCall.context(uid: String?): ExecutionContext {
return AuthenticationContext(uid) + DatastoreContext(datastore) + CacheControlContext()
}
41 changes: 38 additions & 3 deletions service/src/commonMain/kotlin/androidmakers/service/firebase.kt
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,23 @@ import com.google.firebase.FirebaseApp
import com.google.firebase.FirebaseOptions
import com.google.firebase.auth.FirebaseAuth
import com.google.auth.oauth2.GoogleCredentials
import com.google.firebase.auth.AuthErrorCode
import com.google.firebase.auth.FirebaseAuthException


private val lock = Object()
private var _isInitialized = false

fun String.firebaseUid(): String? {
sealed interface FirebaseUidResult {
object Expired: FirebaseUidResult
class Error(val code: String): FirebaseUidResult
class SignedIn(val uid: String): FirebaseUidResult
object SignedOut: FirebaseUidResult
}

fun String.firebaseUid(): FirebaseUidResult {
if (this == "testToken") {
return "testUser"
return FirebaseUidResult.SignedIn("testUser")
}

synchronized(lock) {
Expand All @@ -23,7 +32,33 @@ fun String.firebaseUid(): String? {
}

return try {
FirebaseAuth.getInstance().verifyIdToken(this).uid
FirebaseUidResult.SignedIn(FirebaseAuth.getInstance().verifyIdToken(this).uid)
} catch (e: FirebaseAuthException) {
when (e.authErrorCode) {
AuthErrorCode.EXPIRED_ID_TOKEN -> {
FirebaseUidResult.Expired
}
AuthErrorCode.CERTIFICATE_FETCH_FAILED,
AuthErrorCode.CONFIGURATION_NOT_FOUND,
AuthErrorCode.EMAIL_ALREADY_EXISTS,
AuthErrorCode.EMAIL_NOT_FOUND,
AuthErrorCode.EXPIRED_SESSION_COOKIE,
AuthErrorCode.INVALID_DYNAMIC_LINK_DOMAIN,
AuthErrorCode.INVALID_ID_TOKEN,
AuthErrorCode.INVALID_SESSION_COOKIE,
AuthErrorCode.PHONE_NUMBER_ALREADY_EXISTS,
AuthErrorCode.REVOKED_ID_TOKEN,
AuthErrorCode.REVOKED_SESSION_COOKIE,
AuthErrorCode.TENANT_ID_MISMATCH,
AuthErrorCode.TENANT_NOT_FOUND,
AuthErrorCode.UID_ALREADY_EXISTS,
AuthErrorCode.UNAUTHORIZED_CONTINUE_URL,
AuthErrorCode.USER_NOT_FOUND,
AuthErrorCode.USER_DISABLED,
null -> {
FirebaseUidResult.Error(e.authErrorCode.name)
}
}
} catch (e: Exception) {
e.printStackTrace()
throw e
Expand Down
Loading