capacitor-auth-manager 3.0.0 → 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,96 +2,63 @@ package com.aoneahsan.capacitor_auth_manager;
2
2
 
3
3
  import android.app.Activity;
4
4
  import android.content.Context;
5
- import android.net.Uri;
6
- import android.util.Base64;
7
-
8
- import androidx.core.content.ContextCompat;
9
-
10
- import androidx.credentials.ClearCredentialStateRequest;
11
- import androidx.credentials.Credential;
12
- import androidx.credentials.CredentialManager;
13
- import androidx.credentials.CredentialManagerCallback;
14
- import androidx.credentials.CustomCredential;
15
- import androidx.credentials.GetCredentialRequest;
16
- import androidx.credentials.GetCredentialResponse;
17
- import androidx.credentials.exceptions.ClearCredentialException;
18
- import androidx.credentials.exceptions.GetCredentialCancellationException;
19
- import androidx.credentials.exceptions.GetCredentialException;
20
- import androidx.credentials.exceptions.GetCredentialInterruptedException;
21
- import androidx.credentials.exceptions.NoCredentialException;
22
5
 
23
6
  import com.getcapacitor.JSObject;
24
- import com.google.android.libraries.identity.googleid.GetGoogleIdOption;
25
- import com.google.android.libraries.identity.googleid.GetSignInWithGoogleOption;
26
- import com.google.android.libraries.identity.googleid.GoogleIdTokenCredential;
27
7
 
28
- import org.json.JSONArray;
29
8
  import org.json.JSONObject;
30
9
 
31
- import java.nio.charset.StandardCharsets;
32
- import java.text.SimpleDateFormat;
33
10
  import java.util.ArrayList;
34
- import java.util.Date;
35
11
  import java.util.List;
36
- import java.util.Locale;
37
- import java.util.TimeZone;
38
- import java.util.concurrent.Executor;
39
12
 
40
13
  /**
41
- * Android native Google sign-in built on the modern <b>Credential Manager</b> API
42
- * ({@code androidx.credentials}) + the Google Identity {@code GetGoogleIdOption}.
14
+ * Android native Google sign-in: legacy <b>GoogleSignIn</b> first, <b>Credential Manager</b> as the fallback.
43
15
  *
44
- * <p>This replaces the deprecated {@code com.google.android.gms.auth.api.signin.GoogleSignIn} +
45
- * {@code startActivityForResult(...)} flow, which relied on an {@code onActivityResult} callback the
46
- * plugin never forwarded (so interactive sign-in hung forever). Credential Manager uses an async
47
- * callback ({@link CredentialManagerCallback}) — no {@code onActivityResult} — so that bug class is gone.</p>
16
+ * <p>{@code androidFlow: 'auto'} (the default) runs {@link GoogleLegacySignIn} — the exact path
17
+ * {@code @codetrix-studio/capacitor-google-auth} ran — and falls back to {@link GoogleCredentialManagerSignIn}
18
+ * (bottom sheet, then the "Sign in with Google" button) when GoogleSignIn fails for any reason other than
19
+ * the user cancelling. 3.0.0 ran Credential Manager alone, and Play-installed builds of every production
20
+ * app were refused before any account picker appeared, while the same OAuth clients and SHA-1s had worked
21
+ * through GoogleSignIn in the previous release (2026-10-29). On Android 14+ Credential Manager goes
22
+ * through the system credential service, which can fail with no UI when Google is not an enabled
23
+ * credential provider on the device; GoogleSignIn never touches that service. {@code 'legacy'},
24
+ * {@code 'credential-manager'}, {@code 'bottom-sheet'} and {@code 'button'} pin one path.</p>
48
25
  *
49
- * <p>The package is Firebase-agnostic: this provider returns a credential
50
- * {@code { idToken, ... }} to JS and the app performs its own Firebase
51
- * {@code signInWithCredential(GoogleAuthProvider.credential(idToken))} (or anything else) later.</p>
26
+ * <p>Every error keeps Google's own exception class and message, and configuration errors name the
27
+ * installed package + signing SHA-1 ({@link SigningDiagnostics}), so the cause is readable on the device.</p>
52
28
  *
53
- * <p><b>Limitations of Credential Manager Google sign-in (intentional):</b></p>
54
- * <ul>
55
- * <li>Only an <b>idToken</b> is returned. There is no OAuth access token and no serverAuthCode,
56
- * so {@code credential.accessToken} / {@code credential.serverAuthCode} are intentionally absent.
57
- * Use the Google Authorization API if you need an access token / extra scopes.</li>
58
- * <li>{@code GetGoogleIdOption} does not request additional OAuth scopes, nor honor
59
- * {@code hostedDomain} / {@code loginHint}. Those config values are accepted for API parity but
60
- * are not enforced here.</li>
61
- * <li>There is no server-side revoke; {@code revokeAccess} clears local + Credential Manager state only.</li>
62
- * </ul>
29
+ * <p>The package is Firebase-agnostic: it returns {@code { idToken, ... }} and the app signs in with it.
30
+ * Neither path returns an OAuth access token; extra scopes, server-side revoke and refresh tokens are out
31
+ * of scope for this provider.</p>
63
32
  */
64
33
  public class GoogleAuthProvider implements BaseAuthProvider {
65
- private static final String TAG = "GoogleAuthProvider";
66
- private static final String PROVIDER_ID = "google.com";
67
34
  private static final String STORAGE_CREDENTIAL_KEY = "google";
68
35
  private static final String STORAGE_USER_KEY = "google_user";
69
36
 
70
- private final Context context;
71
- private final Activity activity;
72
37
  private final AuthStorage storage;
73
38
  private final AuthLogger logger;
39
+ private final GoogleLegacySignIn legacy;
40
+ private final GoogleCredentialManagerSignIn credentialManager;
41
+ private ActivityLauncher activityLauncher;
74
42
 
75
43
  private String clientId;
76
44
  private String serverClientId;
77
- // Retained for API parity. Credential Manager's GetGoogleIdOption only returns an ID token and
78
- // cannot request additional OAuth scopes, so non-default scopes are surfaced as a warning only.
45
+ // Retained for API parity: neither Android path requests extra OAuth scopes.
79
46
  private List<String> scopes;
80
47
  private boolean filterByAuthorizedAccounts = false;
81
48
  private boolean autoSelectEnabled = false;
82
49
  private String nonce;
83
50
  private String hostedDomain;
84
51
  private String loginHint;
85
- /** "auto" (bottom sheet, then button on NoCredentialException) | "bottom-sheet" | "button". */
52
+ /** "auto" | "legacy" | "credential-manager" | "bottom-sheet" | "button". */
86
53
  private String androidFlow = "auto";
87
54
 
88
55
  private JSObject currentUser;
89
56
 
90
57
  public GoogleAuthProvider(Context context, Activity activity, AuthStorage storage, AuthLogger logger) {
91
- this.context = context;
92
- this.activity = activity;
93
58
  this.storage = storage;
94
59
  this.logger = logger;
60
+ this.legacy = new GoogleLegacySignIn(context, activity, logger);
61
+ this.credentialManager = new GoogleCredentialManagerSignIn(context, activity, logger);
95
62
  this.scopes = new ArrayList<>();
96
63
  this.scopes.add("email");
97
64
  this.scopes.add("profile");
@@ -99,6 +66,10 @@ public class GoogleAuthProvider implements BaseAuthProvider {
99
66
 
100
67
  // ---- Configuration (populated by ProviderFactory from the google provider options) ----
101
68
 
69
+ public void setActivityLauncher(ActivityLauncher activityLauncher) {
70
+ this.activityLauncher = activityLauncher;
71
+ }
72
+
102
73
  public void setClientId(String clientId) {
103
74
  this.clientId = clientId;
104
75
  }
@@ -143,10 +114,8 @@ public class GoogleAuthProvider implements BaseAuthProvider {
143
114
 
144
115
  @Override
145
116
  public void initialize(CapacitorAuthManager.AuthCallback<Void> callback) {
146
- logger.info("Initializing Google auth provider (Credential Manager)");
117
+ logger.info("Initializing Google auth provider (GoogleSignIn + Credential Manager fallback)");
147
118
  try {
148
- // Credential Manager has no "last signed-in account" concept, so restore any persisted
149
- // profile metadata from storage to keep getCurrentUser() working after a cold start.
150
119
  JSObject storedUser = storage.getUser(STORAGE_USER_KEY);
151
120
  if (storedUser != null) {
152
121
  currentUser = storedUser;
@@ -170,43 +139,114 @@ public class GoogleAuthProvider implements BaseAuthProvider {
170
139
  flow = perCall;
171
140
  }
172
141
  }
173
- logger.info("Starting Google sign-in (Credential Manager, flow=" + flow + ")");
174
-
175
- if ("button".equals(flow)) {
176
- requestSignInWithGoogleButton(callback);
142
+ logger.info("Starting Google sign-in (flow=" + flow + ")");
143
+ if (resolvedServerClientId() == null) {
144
+ callback.onResult(missingClientId());
177
145
  return;
178
146
  }
147
+ warnIfUnsupportedOptions();
148
+ switch (flow) {
149
+ case "legacy":
150
+ runLegacy(profileCallback(callback));
151
+ return;
152
+ case "credential-manager":
153
+ runCredentialManager(profileCallback(callback));
154
+ return;
155
+ case "bottom-sheet":
156
+ credentialManager.requestBottomSheet(resolvedServerClientId(), nonce, filterByAuthorizedAccounts,
157
+ autoSelectEnabled, profileCallback(callback));
158
+ return;
159
+ case "button":
160
+ credentialManager.requestButton(resolvedServerClientId(), nonce, hostedDomain, profileCallback(callback));
161
+ return;
162
+ default:
163
+ runAuto(profileCallback(callback));
164
+ }
165
+ }
179
166
 
180
- final boolean fallbackToButton = !"bottom-sheet".equals(flow);
181
- requestGoogleCredential(filterByAuthorizedAccounts, autoSelectEnabled, new CapacitorAuthManager.AuthCallback<JSObject>() {
167
+ /** GoogleSignIn first; Credential Manager when it fails for any reason other than a cancel. */
168
+ private void runAuto(final GoogleProfileCallback callback) {
169
+ runLegacy(new GoogleProfileCallback() {
182
170
  @Override
183
- public void onResult(CapacitorAuthManager.AuthResult<JSObject> result) {
184
- if (result.isSuccess() || !fallbackToButton || !(result.getError() instanceof NoGoogleCredentialException)) {
185
- callback.onResult(result);
171
+ public void onSuccess(GoogleResultMapper.Profile profile) {
172
+ callback.onSuccess(profile);
173
+ }
174
+
175
+ @Override
176
+ public void onError(final AuthException legacyError) {
177
+ if (isCancellation(legacyError)) {
178
+ callback.onError(legacyError);
186
179
  return;
187
180
  }
188
- // No authorized Google account was offered by the bottom sheet: the explicit
189
- // "Sign in with Google" button flow lets the user pick or add an account.
190
- logger.info("No Google credential from the bottom sheet; falling back to the Sign in with Google button flow");
191
- requestSignInWithGoogleButton(callback);
181
+ logger.warn("Legacy GoogleSignIn failed; trying Credential Manager: " + legacyError.getMessage());
182
+ runCredentialManager(new GoogleProfileCallback() {
183
+ @Override
184
+ public void onSuccess(GoogleResultMapper.Profile profile) {
185
+ callback.onSuccess(profile);
186
+ }
187
+
188
+ @Override
189
+ public void onError(AuthException cmError) {
190
+ if (isCancellation(cmError)) {
191
+ callback.onError(cmError);
192
+ return;
193
+ }
194
+ logger.error("Google sign-in failed on both paths", cmError);
195
+ callback.onError(new AuthException(legacyError.getCode(), legacyError.getMessage()
196
+ + " | Credential Manager: " + cmError.getMessage(), legacyError));
197
+ }
198
+ });
192
199
  }
193
200
  });
194
201
  }
195
202
 
196
- /**
197
- * Marker so signIn() can distinguish "no account offered" from every other failure. It extends
198
- * {@link AuthException} because it also reaches JS unchanged when the caller pinned
199
- * {@code androidFlow: 'bottom-sheet'}, in which case no button fallback runs.
200
- */
201
- private static class NoGoogleCredentialException extends AuthException {
202
- NoGoogleCredentialException(String message) {
203
- super(AuthErrorCodes.SIGN_IN_FAILED, message);
204
- }
203
+ private void runLegacy(GoogleProfileCallback callback) {
204
+ legacy.signIn(resolvedServerClientId(), hostedDomain, loginHint, activityLauncher, callback);
205
+ }
206
+
207
+ /** Credential Manager: bottom sheet, then the button flow when no account is offered. */
208
+ private void runCredentialManager(final GoogleProfileCallback callback) {
209
+ credentialManager.requestBottomSheet(resolvedServerClientId(), nonce, filterByAuthorizedAccounts, autoSelectEnabled,
210
+ new GoogleProfileCallback() {
211
+ @Override
212
+ public void onSuccess(GoogleResultMapper.Profile profile) {
213
+ callback.onSuccess(profile);
214
+ }
215
+
216
+ @Override
217
+ public void onError(AuthException error) {
218
+ if (!(error instanceof GoogleCredentialManagerSignIn.NoGoogleCredentialException)) {
219
+ callback.onError(error);
220
+ return;
221
+ }
222
+ logger.info("No Google credential from the bottom sheet; trying the Sign in with Google button flow");
223
+ credentialManager.requestButton(resolvedServerClientId(), nonce, hostedDomain, callback);
224
+ }
225
+ });
226
+ }
227
+
228
+ private static boolean isCancellation(AuthException error) {
229
+ return AuthErrorCodes.USER_CANCELLED.equals(error.getCode());
230
+ }
231
+
232
+ /** Adapts a path's profile result to the bridge result, persisting the session on success. */
233
+ private GoogleProfileCallback profileCallback(final CapacitorAuthManager.AuthCallback<JSObject> callback) {
234
+ return new GoogleProfileCallback() {
235
+ @Override
236
+ public void onSuccess(GoogleResultMapper.Profile profile) {
237
+ callback.onResult(CapacitorAuthManager.AuthResult.success(completeSignIn(profile)));
238
+ }
239
+
240
+ @Override
241
+ public void onError(AuthException error) {
242
+ callback.onResult(CapacitorAuthManager.AuthResult.error(error));
243
+ }
244
+ };
205
245
  }
206
246
 
207
247
  @Override
208
248
  public void signOut(JSObject options, CapacitorAuthManager.AuthCallback<Void> callback) {
209
- logger.info("Signing out from Google (clearing Credential Manager state)");
249
+ logger.info("Signing out from Google (GoogleSignIn + Credential Manager state)");
210
250
  clearCredentialState(callback);
211
251
  }
212
252
 
@@ -220,19 +260,15 @@ public class GoogleAuthProvider implements BaseAuthProvider {
220
260
 
221
261
  @Override
222
262
  public void refreshToken(JSObject options, final CapacitorAuthManager.AuthCallback<JSObject> callback) {
223
- logger.info("Refreshing Google ID token (silent Credential Manager attempt)");
224
- // A silent attempt only succeeds when exactly one previously-authorized account exists.
225
- requestGoogleCredential(true, true, new CapacitorAuthManager.AuthCallback<JSObject>() {
226
- @Override
227
- public void onResult(CapacitorAuthManager.AuthResult<JSObject> result) {
228
- if (result.isSuccess()) {
229
- callback.onResult(result);
230
- } else {
231
- callback.onResult(CapacitorAuthManager.AuthResult.error(new AuthException(
232
- AuthErrorCodes.TOKEN_REFRESH_FAILED,
233
- "Re-authentication required: could not silently refresh the Google ID token. "
234
- + "Prompt the user to sign in again.")));
235
- }
263
+ logger.info("Refreshing Google ID token (silent attempt)");
264
+ silentSignIn(result -> {
265
+ if (result.isSuccess()) {
266
+ callback.onResult(result);
267
+ } else {
268
+ callback.onResult(CapacitorAuthManager.AuthResult.error(new AuthException(
269
+ AuthErrorCodes.TOKEN_REFRESH_FAILED,
270
+ "Re-authentication required: could not silently refresh the Google ID token. "
271
+ + "Prompt the user to sign in again.")));
236
272
  }
237
273
  });
238
274
  }
@@ -256,380 +292,97 @@ public class GoogleAuthProvider implements BaseAuthProvider {
256
292
  public void getIdToken(boolean forceRefresh, final CapacitorAuthManager.AuthCallback<JSObject> callback) {
257
293
  if (!forceRefresh) {
258
294
  JSObject storedCredential = storage.getCredential(STORAGE_CREDENTIAL_KEY);
259
- if (storedCredential != null) {
260
- String idToken = storedCredential.getString("idToken");
261
- if (idToken != null && !idToken.isEmpty() && isFreshIdToken(idToken)) {
262
- JSObject result = new JSObject();
263
- result.put("token", idToken);
264
- callback.onResult(CapacitorAuthManager.AuthResult.success(result));
295
+ String idToken = storedCredential != null ? storedCredential.getString("idToken") : null;
296
+ if (idToken != null && !idToken.isEmpty() && isFreshIdToken(idToken)) {
297
+ JSObject result = new JSObject();
298
+ result.put("token", idToken);
299
+ callback.onResult(CapacitorAuthManager.AuthResult.success(result));
300
+ return;
301
+ }
302
+ }
303
+ silentSignIn(result -> {
304
+ if (result.isSuccess() && result.getData() != null) {
305
+ JSObject credential = result.getData().getJSObject("credential");
306
+ String idToken = credential != null ? credential.getString("idToken") : null;
307
+ if (idToken != null && !idToken.isEmpty()) {
308
+ JSObject out = new JSObject();
309
+ out.put("token", idToken);
310
+ callback.onResult(CapacitorAuthManager.AuthResult.success(out));
265
311
  return;
266
312
  }
267
313
  }
314
+ callback.onResult(CapacitorAuthManager.AuthResult.error(new AuthException(
315
+ AuthErrorCodes.NO_AUTH_SESSION,
316
+ "No Google ID token available. Re-authentication required.")));
317
+ });
318
+ }
319
+
320
+ /** Silent GoogleSignIn, then a silent Credential Manager attempt. Never shows UI. */
321
+ private void silentSignIn(final CapacitorAuthManager.AuthCallback<JSObject> callback) {
322
+ if (resolvedServerClientId() == null) {
323
+ callback.onResult(missingClientId());
324
+ return;
268
325
  }
326
+ final GoogleProfileCallback done = profileCallback(callback);
327
+ legacy.silentSignIn(resolvedServerClientId(), new GoogleProfileCallback() {
328
+ @Override
329
+ public void onSuccess(GoogleResultMapper.Profile profile) {
330
+ done.onSuccess(profile);
331
+ }
269
332
 
270
- // No cached token (or forced refresh) → silent Credential Manager attempt.
271
- requestGoogleCredential(true, true, new CapacitorAuthManager.AuthCallback<JSObject>() {
272
333
  @Override
273
- public void onResult(CapacitorAuthManager.AuthResult<JSObject> result) {
274
- if (result.isSuccess() && result.getData() != null) {
275
- JSObject credential = result.getData().getJSObject("credential");
276
- String idToken = credential != null ? credential.getString("idToken") : null;
277
- if (idToken != null && !idToken.isEmpty()) {
278
- JSObject out = new JSObject();
279
- out.put("token", idToken);
280
- callback.onResult(CapacitorAuthManager.AuthResult.success(out));
281
- return;
282
- }
283
- }
284
- callback.onResult(CapacitorAuthManager.AuthResult.error(new AuthException(
285
- AuthErrorCodes.NO_AUTH_SESSION,
286
- "No Google ID token available. Re-authentication required.")));
334
+ public void onError(AuthException error) {
335
+ credentialManager.requestBottomSheet(resolvedServerClientId(), nonce, true, true, done);
287
336
  }
288
337
  });
289
338
  }
290
339
 
291
340
  private boolean isFreshIdToken(String idToken) {
292
- try {
293
- return parseIdTokenClaims(idToken).optLong("exp", 0) > System.currentTimeMillis() / 1000;
294
- } catch (Exception invalidToken) {
295
- return false;
296
- }
341
+ JSONObject claims = GoogleResultMapper.parseIdTokenClaims(idToken, logger);
342
+ return claims != null && claims.optLong("exp", 0) > System.currentTimeMillis() / 1000;
297
343
  }
298
344
 
299
345
  @Override
300
346
  public void revokeAccess(String token, CapacitorAuthManager.AuthCallback<Void> callback) {
301
- // Credential Manager has no server-side revoke. Clear the locally-selected account state +
302
- // the persisted session so the next sign-in re-prompts.
303
- logger.info("Revoking Google access (clears local + Credential Manager state only; no server-side revoke)");
347
+ logger.info("Revoking Google access (clears local, GoogleSignIn and Credential Manager state; no server-side revoke)");
304
348
  clearCredentialState(callback);
305
349
  }
306
350
 
307
- // ---- Credential Manager flow ----
308
-
309
- private void requestGoogleCredential(
310
- boolean filterByAuthorized,
311
- boolean autoSelect,
312
- final CapacitorAuthManager.AuthCallback<JSObject> callback
313
- ) {
314
- String resolvedServerClientId = (serverClientId != null && !serverClientId.isEmpty())
315
- ? serverClientId
316
- : clientId;
317
-
318
- if (resolvedServerClientId == null || resolvedServerClientId.isEmpty()) {
319
- callback.onResult(CapacitorAuthManager.AuthResult.error(new AuthException(
320
- AuthErrorCodes.MISSING_CONFIGURATION,
321
- "Google sign-in requires a serverClientId (your Web OAuth client id). "
322
- + "Provide 'serverClientId' (or 'clientId') in the google provider options.")));
323
- return;
324
- }
325
-
326
- if (activity == null) {
327
- callback.onResult(CapacitorAuthManager.AuthResult.error(new AuthException(
328
- AuthErrorCodes.PROVIDER_NOT_INITIALIZED,
329
- "Google sign-in requires a foreground Activity.")));
330
- return;
331
- }
332
-
333
- warnIfUnsupportedOptions();
334
-
335
- try {
336
- GetGoogleIdOption.Builder optionBuilder = new GetGoogleIdOption.Builder()
337
- .setServerClientId(resolvedServerClientId)
338
- .setFilterByAuthorizedAccounts(filterByAuthorized)
339
- .setAutoSelectEnabled(autoSelect);
340
-
341
- if (nonce != null && !nonce.isEmpty()) {
342
- optionBuilder.setNonce(nonce);
343
- }
344
-
345
- GetGoogleIdOption googleIdOption = optionBuilder.build();
346
-
347
- GetCredentialRequest request = new GetCredentialRequest.Builder()
348
- .addCredentialOption(googleIdOption)
349
- .build();
350
-
351
- launchCredentialRequest(request, callback);
352
- } catch (Exception e) {
353
- logger.error("Failed to start Google Credential Manager request", e);
354
- callback.onResult(CapacitorAuthManager.AuthResult.error(new AuthException(
355
- AuthErrorCodes.SIGN_IN_FAILED,
356
- "Failed to start Google sign-in: " + e.getMessage(), e)));
357
- }
358
- }
359
-
360
- /**
361
- * The explicit "Sign in with Google" button flow ({@link GetSignInWithGoogleOption}). Unlike the
362
- * bottom sheet it always shows the account chooser and can add a new Google account, so it is the
363
- * right fallback when {@code NoCredentialException} is raised. Same result shape (ID token).
364
- */
365
- private void requestSignInWithGoogleButton(final CapacitorAuthManager.AuthCallback<JSObject> callback) {
366
- String resolvedServerClientId = (serverClientId != null && !serverClientId.isEmpty())
367
- ? serverClientId
368
- : clientId;
369
-
370
- if (resolvedServerClientId == null || resolvedServerClientId.isEmpty()) {
371
- callback.onResult(CapacitorAuthManager.AuthResult.error(new AuthException(
372
- AuthErrorCodes.MISSING_CONFIGURATION,
373
- "Google sign-in requires a serverClientId (your Web OAuth client id). "
374
- + "Provide 'serverClientId' (or 'clientId') in the google provider options.")));
375
- return;
376
- }
377
-
378
- if (activity == null) {
379
- callback.onResult(CapacitorAuthManager.AuthResult.error(new AuthException(
380
- AuthErrorCodes.PROVIDER_NOT_INITIALIZED,
381
- "Google sign-in requires a foreground Activity.")));
382
- return;
383
- }
384
-
385
- try {
386
- GetSignInWithGoogleOption.Builder optionBuilder = new GetSignInWithGoogleOption.Builder(resolvedServerClientId);
387
- if (nonce != null && !nonce.isEmpty()) {
388
- optionBuilder.setNonce(nonce);
389
- }
390
- if (hostedDomain != null && !hostedDomain.isEmpty()) {
391
- optionBuilder.setHostedDomainFilter(hostedDomain);
392
- }
393
-
394
- GetCredentialRequest request = new GetCredentialRequest.Builder()
395
- .addCredentialOption(optionBuilder.build())
396
- .build();
397
-
398
- launchCredentialRequest(request, callback);
399
- } catch (Exception e) {
400
- logger.error("Failed to start the Sign in with Google button flow", e);
401
- callback.onResult(CapacitorAuthManager.AuthResult.error(new AuthException(
402
- AuthErrorCodes.SIGN_IN_FAILED,
403
- "Failed to start the Sign in with Google button flow: " + e.getMessage(), e)));
404
- }
405
- }
406
-
407
- private void launchCredentialRequest(
408
- GetCredentialRequest request,
409
- final CapacitorAuthManager.AuthCallback<JSObject> callback
410
- ) {
411
- CredentialManager credentialManager = CredentialManager.create(context);
412
- Executor executor = ContextCompat.getMainExecutor(context);
413
-
414
- credentialManager.getCredentialAsync(
415
- activity,
416
- request,
417
- null,
418
- executor,
419
- new CredentialManagerCallback<GetCredentialResponse, GetCredentialException>() {
420
- @Override
421
- public void onResult(GetCredentialResponse response) {
422
- handleSignInResponse(response, callback);
423
- }
424
-
425
- @Override
426
- public void onError(GetCredentialException e) {
427
- handleSignInError(e, callback);
428
- }
429
- }
430
- );
431
- }
432
-
433
- private void handleSignInResponse(
434
- GetCredentialResponse response,
435
- CapacitorAuthManager.AuthCallback<JSObject> callback
436
- ) {
437
- try {
438
- Credential credential = response.getCredential();
439
- if (credential instanceof CustomCredential
440
- && GoogleIdTokenCredential.TYPE_GOOGLE_ID_TOKEN_CREDENTIAL.equals(credential.getType())) {
441
-
442
- GoogleIdTokenCredential googleCredential =
443
- GoogleIdTokenCredential.createFrom(((CustomCredential) credential).getData());
444
-
445
- JSONObject claims = parseIdTokenClaims(googleCredential.getIdToken());
446
-
447
- JSObject user = createUserObject(googleCredential, claims);
448
- JSObject credentialObj = createCredentialObject(googleCredential);
449
-
450
- currentUser = user;
451
- persistSession(user, credentialObj);
452
-
453
- JSObject result = new JSObject();
454
- result.put("user", user);
455
- result.put("credential", credentialObj);
456
-
457
- JSObject additionalUserInfo = new JSObject();
458
- additionalUserInfo.put("isNewUser", false);
459
- additionalUserInfo.put("providerId", PROVIDER_ID);
460
- if (googleCredential.getId() != null) {
461
- additionalUserInfo.put("username", googleCredential.getId());
462
- }
463
- result.put("additionalUserInfo", additionalUserInfo);
464
- result.put("operationType", "signIn");
351
+ // ---- Helpers ----
465
352
 
466
- logger.info("Google sign-in successful (Credential Manager)");
467
- callback.onResult(CapacitorAuthManager.AuthResult.success(result));
468
- } else {
469
- String type = credential != null ? credential.getType() : "null";
470
- logger.error("Unexpected credential type from Credential Manager: " + type, null);
471
- callback.onResult(CapacitorAuthManager.AuthResult.error(new AuthException(
472
- AuthErrorCodes.INVALID_CREDENTIALS,
473
- "Unexpected credential type returned from Google sign-in: " + type)));
474
- }
475
- } catch (Exception e) {
476
- // Covers a malformed credential / ID-token parse failure. (googleid 1.1.1's
477
- // GoogleIdTokenCredential.createFrom does not declare a checked exception.)
478
- logger.error("Unexpected error handling Google credential", e);
479
- callback.onResult(CapacitorAuthManager.AuthResult.error(new AuthException(
480
- AuthErrorCodes.INVALID_CREDENTIALS,
481
- "Could not read the Google credential: " + e.getMessage(), e)));
353
+ private String resolvedServerClientId() {
354
+ if (serverClientId != null && !serverClientId.isEmpty()) {
355
+ return serverClientId;
482
356
  }
357
+ return clientId != null && !clientId.isEmpty() ? clientId : null;
483
358
  }
484
359
 
485
- private void handleSignInError(
486
- GetCredentialException e,
487
- CapacitorAuthManager.AuthCallback<JSObject> callback
488
- ) {
489
- if (e instanceof GetCredentialCancellationException) {
490
- logger.info("Google sign-in cancelled by user");
491
- callback.onResult(CapacitorAuthManager.AuthResult.error(new AuthException(
492
- AuthErrorCodes.USER_CANCELLED, "User cancelled Google sign-in")));
493
- return;
494
- }
495
- if (e instanceof GetCredentialInterruptedException) {
496
- // Transient: Play services restarted or the device lost connectivity mid-request.
497
- logger.warn("Google sign-in interrupted; the caller may retry");
498
- callback.onResult(CapacitorAuthManager.AuthResult.error(new AuthException(
499
- AuthErrorCodes.NETWORK_ERROR,
500
- "Google sign-in was interrupted. Check the connection and try again.")));
501
- return;
502
- }
503
- if (e instanceof NoCredentialException) {
504
- logger.warn("No Google credentials available for sign-in");
505
- callback.onResult(CapacitorAuthManager.AuthResult.error(new NoGoogleCredentialException(
506
- "No Google account available. Add a Google account to the device, or ensure "
507
- + "Google Play services is up to date and the SHA-1 fingerprint is registered.")));
508
- return;
509
- }
510
- logger.error("Google sign-in failed: " + e.getClass().getSimpleName(), e);
511
- callback.onResult(CapacitorAuthManager.AuthResult.error(new AuthException(
512
- AuthErrorCodes.SIGN_IN_FAILED,
513
- "Google sign-in failed: " + e.getMessage(), e)));
360
+ private static CapacitorAuthManager.AuthResult<JSObject> missingClientId() {
361
+ return CapacitorAuthManager.AuthResult.error(new AuthException(
362
+ AuthErrorCodes.MISSING_CONFIGURATION,
363
+ "Google sign-in requires a serverClientId (your Web OAuth client id). "
364
+ + "Provide 'serverClientId' (or 'clientId') in the google provider options."));
514
365
  }
515
366
 
516
367
  private void clearCredentialState(final CapacitorAuthManager.AuthCallback<Void> callback) {
517
- try {
518
- CredentialManager credentialManager = CredentialManager.create(context);
519
- Executor executor = ContextCompat.getMainExecutor(context);
520
- credentialManager.clearCredentialStateAsync(
521
- new ClearCredentialStateRequest(),
522
- null,
523
- executor,
524
- new CredentialManagerCallback<Void, ClearCredentialException>() {
525
- @Override
526
- public void onResult(Void unused) {
527
- clearSession();
528
- callback.onResult(CapacitorAuthManager.AuthResult.success(null));
529
- }
530
-
531
- @Override
532
- public void onError(ClearCredentialException e) {
533
- logger.error("Failed to clear Credential Manager state", e);
534
- // Still clear local session so the app reflects a signed-out state.
535
- clearSession();
536
- callback.onResult(CapacitorAuthManager.AuthResult.success(null));
537
- }
538
- }
539
- );
540
- } catch (Exception e) {
541
- logger.error("Error clearing Credential Manager state", e);
368
+ legacy.signOut();
369
+ credentialManager.clearState(() -> {
542
370
  clearSession();
543
371
  callback.onResult(CapacitorAuthManager.AuthResult.success(null));
544
- }
545
- }
546
-
547
- // ---- Result building ----
548
-
549
- private JSObject createUserObject(GoogleIdTokenCredential cred, JSONObject claims) {
550
- String email = cred.getId();
551
- String displayName = cred.getDisplayName();
552
- Uri photoUri = cred.getProfilePictureUri();
553
- String photoURL = photoUri != null ? photoUri.toString() : null;
554
- String phoneNumber = null; // Google ID tokens do not provide a phone number.
555
-
556
- String uid = null;
557
- boolean emailVerified = true;
558
- if (claims != null) {
559
- String sub = claims.optString("sub", null);
560
- if (sub != null && !sub.isEmpty()) {
561
- uid = sub;
562
- }
563
- if (claims.has("email_verified")) {
564
- emailVerified = claims.optBoolean("email_verified", true);
565
- }
566
- if (email == null) {
567
- email = claims.optString("email", null);
568
- }
569
- if (displayName == null) {
570
- displayName = claims.optString("name", null);
571
- }
572
- if (photoURL == null) {
573
- String picture = claims.optString("picture", null);
574
- if (picture != null && !picture.isEmpty()) {
575
- photoURL = picture;
576
- }
577
- }
578
- }
579
- if (uid == null || uid.isEmpty()) {
580
- // Credential Manager doesn't expose the Google `sub` directly; fall back to the email id.
581
- uid = email;
582
- }
583
-
584
- JSObject user = new JSObject();
585
- user.put("uid", uid);
586
- user.put("email", email);
587
- user.put("emailVerified", emailVerified);
588
- user.put("displayName", displayName);
589
- user.put("photoURL", photoURL);
590
- user.put("phoneNumber", phoneNumber);
591
- user.put("isAnonymous", false);
592
- // tenantId / refreshToken intentionally omitted (not available from Credential Manager).
593
-
594
- JSONArray providerData = new JSONArray();
595
- JSObject providerEntry = new JSObject();
596
- providerEntry.put("providerId", PROVIDER_ID);
597
- providerEntry.put("uid", uid);
598
- providerEntry.put("displayName", displayName);
599
- providerEntry.put("email", email);
600
- providerEntry.put("phoneNumber", phoneNumber);
601
- providerEntry.put("photoURL", photoURL);
602
- providerData.put(providerEntry);
603
- user.put("providerData", providerData);
604
-
605
- JSObject metadata = new JSObject();
606
- SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US);
607
- sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
608
- metadata.put("lastSignInTime", sdf.format(new Date()));
609
- user.put("metadata", metadata);
610
-
611
- return user;
612
- }
613
-
614
- private JSObject createCredentialObject(GoogleIdTokenCredential cred) {
615
- JSObject credential = new JSObject();
616
- credential.put("providerId", PROVIDER_ID);
617
- credential.put("signInMethod", PROVIDER_ID);
618
- credential.put("idToken", cred.getIdToken());
619
- // accessToken and serverAuthCode are NOT provided by Credential Manager sign-in (ID token only) —
620
- // intentionally absent. Consumers feed credential.idToken into their own signInWithCredential(...).
621
- return credential;
372
+ });
622
373
  }
623
374
 
624
- // ---- Helpers ----
625
-
626
- private void persistSession(JSObject user, JSObject credential) {
375
+ /** Builds the shared result shape, keeps the user in memory and persists the session. */
376
+ private JSObject completeSignIn(GoogleResultMapper.Profile profile) {
377
+ JSObject result = GoogleResultMapper.buildResult(profile, logger);
378
+ currentUser = result.getJSObject("user");
627
379
  try {
628
- storage.saveCredential(STORAGE_CREDENTIAL_KEY, credential);
629
- storage.saveUser(STORAGE_USER_KEY, user);
380
+ storage.saveCredential(STORAGE_CREDENTIAL_KEY, result.getJSObject("credential"));
381
+ storage.saveUser(STORAGE_USER_KEY, currentUser);
630
382
  } catch (Exception e) {
631
383
  logger.warn("Failed to persist Google session");
632
384
  }
385
+ return result;
633
386
  }
634
387
 
635
388
  private void clearSession() {
@@ -639,43 +392,11 @@ public class GoogleAuthProvider implements BaseAuthProvider {
639
392
  }
640
393
 
641
394
  private void warnIfUnsupportedOptions() {
642
- if (hostedDomain != null || loginHint != null) {
643
- logger.warn("hostedDomain/loginHint are not enforced by Android Credential Manager "
644
- + "(GetGoogleIdOption) and will be ignored");
645
- }
646
- if (scopes != null && !scopes.isEmpty()) {
647
- for (String scope : scopes) {
648
- if (scope != null
649
- && !scope.equals("email")
650
- && !scope.equals("profile")
651
- && !scope.equals("openid")) {
652
- logger.warn("Additional OAuth scopes are ignored by Android Credential Manager Google "
653
- + "sign-in (ID token only). Use the Google Authorization API for extra scopes.");
654
- break;
655
- }
656
- }
657
- }
658
- }
659
-
660
- /**
661
- * Best-effort decode of the (unverified) ID-token JWT payload to read claims such as {@code sub}
662
- * and {@code email_verified}. The token's signature is verified server-side by the consumer's
663
- * own {@code signInWithCredential}; this is only used to enrich the user object.
664
- */
665
- private JSONObject parseIdTokenClaims(String idToken) {
666
- if (idToken == null || idToken.isEmpty()) {
667
- return null;
668
- }
669
- try {
670
- String[] parts = idToken.split("\\.");
671
- if (parts.length < 2) {
672
- return null;
395
+ for (String scope : scopes) {
396
+ if (scope != null && !scope.equals("email") && !scope.equals("profile") && !scope.equals("openid")) {
397
+ logger.warn("Additional OAuth scopes are ignored by Android Google sign-in (ID token only).");
398
+ break;
673
399
  }
674
- byte[] decoded = Base64.decode(parts[1], Base64.URL_SAFE | Base64.NO_PADDING | Base64.NO_WRAP);
675
- return new JSONObject(new String(decoded, StandardCharsets.UTF_8));
676
- } catch (Exception e) {
677
- logger.warn("Failed to parse Google ID token claims");
678
- return null;
679
400
  }
680
401
  }
681
402
  }