Skip to content

Commit 006f504

Browse files
committed
fix(mobile): resolve Google Sign-In web client ID from google-services.json
- Pass applicationContext into FirebaseAuthRepository so it can read the default_web_client_id string resource generated by the google-services plugin from google-services.json - resolveWebClientId() tries the generated resource first, then falls back to BuildConfig.GOOGLE_WEB_CLIENT_ID (local.properties) - Handle NoCredentialException by launching Settings.ACTION_ADD_ACCOUNT so users with no Google account on device are guided to add one - GOOGLE_WEB_CLIENT_ID retained in BuildConfig as fallback for environments where google-services.json lacks the web OAuth client
1 parent 079668d commit 006f504

2 files changed

Lines changed: 56 additions & 23 deletions

File tree

‎mobile/app/src/main/java/com/company/template/MainActivity.kt‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ class MainActivity : ComponentActivity() {
3939
private val requestNotificationPermission =
4040
registerForActivityResult(ActivityResultContracts.RequestPermission()) { /* no-op */ }
4141

42-
private val authRepository by lazy { FirebaseAuthRepository() }
42+
private val authRepository by lazy { FirebaseAuthRepository(applicationContext) }
4343
private val onboardingRepository by lazy { DataStoreOnboardingRepository(applicationContext) }
4444

4545
private val authViewModel: AuthViewModel by viewModels {

‎mobile/app/src/main/java/com/company/template/auth/FirebaseAuthRepository.kt‎

Lines changed: 55 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -2,28 +2,32 @@ package com.company.template.auth
22

33
import android.app.Activity
44
import android.content.Context
5+
import android.content.Intent
6+
import android.provider.Settings
57
import androidx.credentials.CredentialManager
68
import androidx.credentials.CustomCredential
79
import androidx.credentials.GetCredentialRequest
10+
import androidx.credentials.exceptions.NoCredentialException
811
import com.company.template.BuildConfig
912
import com.google.android.libraries.identity.googleid.GetGoogleIdOption
1013
import com.google.android.libraries.identity.googleid.GoogleIdTokenCredential
1114
import com.google.firebase.auth.FirebaseAuth
1215
import com.google.firebase.auth.FirebaseUser
1316
import com.google.firebase.auth.GoogleAuthProvider
1417
import com.google.firebase.auth.UserProfileChangeRequest
18+
import kotlinx.coroutines.CoroutineScope
19+
import kotlinx.coroutines.Dispatchers
20+
import kotlinx.coroutines.SupervisorJob
1521
import kotlinx.coroutines.channels.awaitClose
16-
import kotlinx.coroutines.flow.callbackFlow
1722
import kotlinx.coroutines.flow.SharingStarted
1823
import kotlinx.coroutines.flow.StateFlow
24+
import kotlinx.coroutines.flow.callbackFlow
1925
import kotlinx.coroutines.flow.stateIn
20-
import kotlinx.coroutines.CoroutineScope
21-
import kotlinx.coroutines.Dispatchers
22-
import kotlinx.coroutines.SupervisorJob
2326
import kotlinx.coroutines.tasks.await
2427

2528
class FirebaseAuthRepository(
26-
private val auth: FirebaseAuth = FirebaseAuth.getInstance()
29+
private val context: Context,
30+
private val auth: FirebaseAuth = FirebaseAuth.getInstance(),
2731
) : AuthRepository {
2832

2933
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
@@ -40,7 +44,7 @@ class FirebaseAuthRepository(
4044
.stateIn(
4145
scope = scope,
4246
started = SharingStarted.WhileSubscribed(5_000),
43-
initialValue = auth.currentUser
47+
initialValue = auth.currentUser,
4448
)
4549

4650
override suspend fun signInWithEmail(email: String, password: String): Result<Unit> =
@@ -52,7 +56,7 @@ class FirebaseAuthRepository(
5256
override suspend fun registerWithEmail(
5357
name: String,
5458
email: String,
55-
password: String
59+
password: String,
5660
): Result<Unit> = runCatching {
5761
val result = auth.createUserWithEmailAndPassword(email, password).await()
5862
val profileUpdates = UserProfileChangeRequest.Builder()
@@ -63,36 +67,65 @@ class FirebaseAuthRepository(
6367
}
6468

6569
override suspend fun signInWithGoogle(activity: Activity): Result<Unit> = runCatching {
66-
val credentialManager = CredentialManager.create(activity)
70+
val webClientId = resolveWebClientId()
71+
check(webClientId.isNotEmpty()) {
72+
"Google Sign-In not configured.\n" +
73+
"Option 1 (recommended): Enable Google Sign-In in Firebase Console " +
74+
"(Authentication → Sign-in method → Google) then re-download google-services.json.\n" +
75+
"Option 2: Add GOOGLE_WEB_CLIENT_ID=<web-client-id> to mobile/local.properties."
76+
}
6777

78+
val credentialManager = CredentialManager.create(activity)
6879
val googleIdOption = GetGoogleIdOption.Builder()
6980
.setFilterByAuthorizedAccounts(false)
70-
.setServerClientId(BuildConfig.GOOGLE_WEB_CLIENT_ID)
81+
.setServerClientId(webClientId)
7182
.build()
7283

7384
val request = GetCredentialRequest.Builder()
7485
.addCredentialOption(googleIdOption)
7586
.build()
7687

77-
val result = credentialManager.getCredential(activity, request)
78-
val credential = result.credential
79-
80-
if (credential is CustomCredential &&
81-
credential.type == GoogleIdTokenCredential.TYPE_GOOGLE_ID_TOKEN_CREDENTIAL
82-
) {
83-
val googleIdTokenCredential = GoogleIdTokenCredential.createFrom(credential.data)
84-
val firebaseCredential = GoogleAuthProvider.getCredential(
85-
googleIdTokenCredential.idToken,
86-
null
88+
val credentialResult = try {
89+
credentialManager.getCredential(activity, request)
90+
} catch (e: NoCredentialException) {
91+
// No Google account on this device — send the user to add one
92+
activity.startActivity(
93+
Intent(Settings.ACTION_ADD_ACCOUNT).apply {
94+
putExtra(Settings.EXTRA_ACCOUNT_TYPES, arrayOf("com.google"))
95+
}
8796
)
88-
auth.signInWithCredential(firebaseCredential).await()
89-
} else {
90-
error("Unexpected credential type: ${credential.type}")
97+
error("No Google account found. Please add a Google account and try again.")
9198
}
99+
100+
val credential = credentialResult.credential
101+
check(
102+
credential is CustomCredential &&
103+
credential.type == GoogleIdTokenCredential.TYPE_GOOGLE_ID_TOKEN_CREDENTIAL
104+
) { "Unexpected credential type: ${credential.type}" }
105+
106+
val googleIdTokenCredential = GoogleIdTokenCredential.createFrom(credential.data)
107+
val firebaseCredential = GoogleAuthProvider.getCredential(
108+
googleIdTokenCredential.idToken,
109+
null,
110+
)
111+
auth.signInWithCredential(firebaseCredential).await()
92112
Unit
93113
}
94114

95115
override suspend fun signOut() {
96116
auth.signOut()
97117
}
118+
119+
// Prefer the resource generated by the google-services plugin from google-services.json;
120+
// fall back to the BuildConfig field populated from local.properties.
121+
private fun resolveWebClientId(): String {
122+
val resId = context.resources.getIdentifier(
123+
"default_web_client_id", "string", context.packageName
124+
)
125+
if (resId != 0) {
126+
val fromResource = context.getString(resId)
127+
if (fromResource.isNotEmpty()) return fromResource
128+
}
129+
return BuildConfig.GOOGLE_WEB_CLIENT_ID
130+
}
98131
}

0 commit comments

Comments
 (0)