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