@capgo/capacitor-social-login 8.7.4 → 8.7.6

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.
@@ -1,5 +1,6 @@
1
1
  package ee.forgr.capacitor.social.login;
2
2
 
3
+ import android.accounts.Account;
3
4
  import android.app.Activity;
4
5
  import android.app.PendingIntent;
5
6
  import android.content.Context;
@@ -34,8 +35,11 @@ import com.google.android.libraries.identity.googleid.GetGoogleIdOption;
34
35
  import com.google.android.libraries.identity.googleid.GetSignInWithGoogleOption;
35
36
  import com.google.android.libraries.identity.googleid.GoogleIdTokenCredential;
36
37
  import com.google.common.util.concurrent.ListenableFuture;
38
+ import ee.forgr.capacitor.social.login.helpers.PluginHttpClient;
37
39
  import ee.forgr.capacitor.social.login.helpers.SocialProvider;
38
40
  import java.io.IOException;
41
+ import java.net.URLEncoder;
42
+ import java.nio.charset.StandardCharsets;
39
43
  import java.security.MessageDigest;
40
44
  import java.security.NoSuchAlgorithmException;
41
45
  import java.util.ArrayList;
@@ -43,16 +47,13 @@ import java.util.HashSet;
43
47
  import java.util.List;
44
48
  import java.util.Objects;
45
49
  import java.util.Set;
50
+ import java.util.concurrent.ExecutionException;
46
51
  import java.util.concurrent.Executor;
47
52
  import java.util.concurrent.ExecutorService;
48
53
  import java.util.concurrent.Executors;
49
54
  import java.util.concurrent.TimeUnit;
50
- import okhttp3.Call;
51
- import okhttp3.Callback;
52
- import okhttp3.OkHttpClient;
53
- import okhttp3.Request;
54
- import okhttp3.Response;
55
- import okhttp3.ResponseBody;
55
+ import java.util.concurrent.TimeoutException;
56
+ import java.util.concurrent.atomic.AtomicBoolean;
56
57
  import org.json.JSONArray;
57
58
  import org.json.JSONException;
58
59
  import org.json.JSONObject;
@@ -88,7 +89,33 @@ public class GoogleProvider implements SocialProvider {
88
89
  private String idToken = null;
89
90
  private String accessToken = null;
90
91
  private GoogleProviderLoginType mode = GoogleProviderLoginType.ONLINE;
92
+ private boolean skipAuthOnlyAuthorizationAfterSignIn = false;
91
93
  private String hostedDomain = null;
94
+ private Integer pendingAuthorizationSlotIndex = null;
95
+
96
+ private static final class AuthorizationWaitContext {
97
+
98
+ private final AtomicBoolean finished = new AtomicBoolean(false);
99
+ private final AtomicBoolean consentUiLaunched = new AtomicBoolean(false);
100
+ private final int[] slotIndex = new int[] { -1 };
101
+ private CallbackToFutureAdapter.Completer<AuthorizationResult> slotCompleter = null;
102
+
103
+ private void markFinished() {
104
+ finished.set(true);
105
+ }
106
+
107
+ private boolean isFinished() {
108
+ return finished.get();
109
+ }
110
+
111
+ private void markConsentUiLaunched() {
112
+ consentUiLaunched.set(true);
113
+ }
114
+
115
+ private boolean isConsentUiLaunched() {
116
+ return consentUiLaunched.get();
117
+ }
118
+ }
92
119
 
93
120
  private static String maskClientId(String clientId) {
94
121
  if (clientId == null || clientId.isEmpty()) {
@@ -174,9 +201,19 @@ public class GoogleProvider implements SocialProvider {
174
201
  }
175
202
 
176
203
  public void initialize(String clientId, GoogleProviderLoginType mode, String hostedDomain) {
204
+ initialize(clientId, mode, hostedDomain, false);
205
+ }
206
+
207
+ public void initialize(
208
+ String clientId,
209
+ GoogleProviderLoginType mode,
210
+ String hostedDomain,
211
+ boolean skipAuthOnlyAuthorizationAfterSignIn
212
+ ) {
177
213
  this.credentialManager = CredentialManager.create(activity);
178
214
  this.clientId = clientId;
179
215
  this.mode = mode;
216
+ this.skipAuthOnlyAuthorizationAfterSignIn = skipAuthOnlyAuthorizationAfterSignIn;
180
217
  this.hostedDomain = hostedDomain;
181
218
  logGoogleCloudDiagnostics("initialize");
182
219
 
@@ -189,8 +226,16 @@ public class GoogleProvider implements SocialProvider {
189
226
  try {
190
227
  JSONObject object = new JSONObject(data);
191
228
  GoogleProvider.this.idToken = object.optString("idToken", null);
192
- String restoredAccessToken = object.optString("accessToken", null);
193
- GoogleProvider.this.accessToken = restoredAccessToken != null && !restoredAccessToken.isEmpty() ? restoredAccessToken : null;
229
+ if (!object.has("accessToken") || object.isNull("accessToken")) {
230
+ GoogleProvider.this.accessToken = null;
231
+ } else {
232
+ String restoredAccessToken = object.optString("accessToken", null);
233
+ if (restoredAccessToken == null || restoredAccessToken.isEmpty() || "null".equals(restoredAccessToken)) {
234
+ GoogleProvider.this.accessToken = null;
235
+ } else {
236
+ GoogleProvider.this.accessToken = restoredAccessToken;
237
+ }
238
+ }
194
239
  JSONArray storedScopes = object.optJSONArray("scopes");
195
240
  if (storedScopes != null && storedScopes.length() > 0) {
196
241
  List<String> scopesList = new ArrayList<>(storedScopes.length());
@@ -219,31 +264,6 @@ public class GoogleProvider implements SocialProvider {
219
264
  }
220
265
  }
221
266
 
222
- /**
223
- * Authentication-only (OIDC) scopes that Credential Manager already covers via the ID token.
224
- * AuthorizationClient is only needed when requesting additional Google API scopes.
225
- */
226
- private static boolean isAuthenticationOnlyScopes(String[] scopes) {
227
- if (scopes == null || scopes.length == 0) {
228
- return true;
229
- }
230
- for (String scope : scopes) {
231
- if (scope == null || scope.isEmpty()) {
232
- continue;
233
- }
234
- boolean isDefault =
235
- scope.equals("openid") ||
236
- scope.equals("https://www.googleapis.com/auth/userinfo.email") ||
237
- scope.equals("https://www.googleapis.com/auth/userinfo.profile") ||
238
- scope.equals("email") ||
239
- scope.equals("profile");
240
- if (!isDefault) {
241
- return false;
242
- }
243
- }
244
- return true;
245
- }
246
-
247
267
  private void resolveOnlineLogin(
248
268
  PluginCall call,
249
269
  JSObject response,
@@ -275,121 +295,117 @@ public class GoogleProvider implements SocialProvider {
275
295
 
276
296
  public ListenableFuture<Boolean> accessTokenIsValid(String accessToken) {
277
297
  return CallbackToFutureAdapter.getFuture((completer) -> {
278
- OkHttpClient client = new OkHttpClient();
279
- Request tokenRequest = new Request.Builder().url(TOKEN_REQUEST_URL + "?" + "access_token=" + accessToken).get().build();
280
-
281
- client
282
- .newCall(tokenRequest)
283
- .enqueue(
284
- new Callback() {
285
- @Override
286
- public void onFailure(@NonNull Call call, @NonNull IOException e) {}
298
+ String url = TOKEN_REQUEST_URL + "?access_token=" + URLEncoder.encode(accessToken, StandardCharsets.UTF_8.name());
299
+ PluginHttpClient.DEFAULT.enqueueGet(
300
+ url,
301
+ null,
302
+ new PluginHttpClient.Callback() {
303
+ @Override
304
+ public void onFailure(IOException e) {
305
+ completer.setException(e);
306
+ }
287
307
 
288
- @Override
289
- public void onResponse(@NonNull Call httpCall, @NonNull Response httpResponse) throws IOException {
290
- if (!httpResponse.isSuccessful()) {
291
- completer.set(false);
292
- Log.i(
293
- LOG_TAG,
294
- String.format(
295
- "Invalid response from %s. Response not successful. Status code: %s. Assuming that the token is not valid",
296
- TOKEN_REQUEST_URL,
297
- httpResponse.code()
298
- )
299
- );
300
- return;
301
- }
308
+ @Override
309
+ public void onResponse(int code, String responseString) throws IOException {
310
+ if (!PluginHttpClient.isSuccessfulHttpCode(code)) {
311
+ completer.set(false);
312
+ Log.i(
313
+ LOG_TAG,
314
+ String.format(
315
+ "Invalid response from %s. Response not successful. Status code: %s. Assuming that the token is not valid",
316
+ TOKEN_REQUEST_URL,
317
+ code
318
+ )
319
+ );
320
+ return;
321
+ }
302
322
 
303
- ResponseBody responseBody = httpResponse.body();
304
- if (responseBody == null) {
305
- completer.setException(
306
- new RuntimeException(
307
- String.format("Invalid response from %s. Response body is null", TOKEN_REQUEST_URL)
308
- )
309
- );
310
- Log.e(LOG_TAG, String.format("Invalid response from %s. Response body is null", TOKEN_REQUEST_URL));
311
- return;
312
- }
323
+ if (responseString == null || responseString.isEmpty()) {
324
+ completer.setException(
325
+ new RuntimeException(String.format("Invalid response from %s. Response body is null", TOKEN_REQUEST_URL))
326
+ );
327
+ Log.e(LOG_TAG, String.format("Invalid response from %s. Response body is null", TOKEN_REQUEST_URL));
328
+ return;
329
+ }
313
330
 
314
- String responseString = responseBody.string();
315
- JSONObject jsonObject;
316
- try {
317
- jsonObject = (JSONObject) new JSONTokener(responseString).nextValue();
318
- } catch (JSONException e) {
319
- completer.setException(
320
- new RuntimeException(
321
- String.format(
322
- "Invalid response from %s. Response body is not a valid JSON. Error: %s",
323
- TOKEN_REQUEST_URL,
324
- e
325
- )
326
- )
327
- );
328
- Log.e(
329
- LOG_TAG,
331
+ JSONObject jsonObject;
332
+ try {
333
+ jsonObject = (JSONObject) new JSONTokener(responseString).nextValue();
334
+ } catch (JSONException e) {
335
+ completer.setException(
336
+ new RuntimeException(
330
337
  String.format(
331
338
  "Invalid response from %s. Response body is not a valid JSON. Error: %s",
332
339
  TOKEN_REQUEST_URL,
333
340
  e
334
341
  )
335
- );
336
- return;
337
- }
342
+ )
343
+ );
344
+ Log.e(
345
+ LOG_TAG,
346
+ String.format(
347
+ "Invalid response from %s. Response body is not a valid JSON. Error: %s",
348
+ TOKEN_REQUEST_URL,
349
+ e
350
+ )
351
+ );
352
+ return;
353
+ }
338
354
 
339
- String expiresIn;
340
- try {
341
- expiresIn = jsonObject.getString("expires_in");
342
- } catch (JSONException e) {
343
- completer.setException(
344
- new RuntimeException(
345
- String.format(
346
- "Invalid response from %s. Response JSON does not include expires_in. Error: %s",
347
- TOKEN_REQUEST_URL,
348
- e
349
- )
350
- )
351
- );
352
- Log.e(
353
- LOG_TAG,
355
+ String expiresIn;
356
+ try {
357
+ expiresIn = jsonObject.getString("expires_in");
358
+ } catch (JSONException e) {
359
+ completer.setException(
360
+ new RuntimeException(
354
361
  String.format(
355
362
  "Invalid response from %s. Response JSON does not include expires_in. Error: %s",
356
363
  TOKEN_REQUEST_URL,
357
364
  e
358
365
  )
359
- );
360
- return;
361
- }
366
+ )
367
+ );
368
+ Log.e(
369
+ LOG_TAG,
370
+ String.format(
371
+ "Invalid response from %s. Response JSON does not include expires_in. Error: %s",
372
+ TOKEN_REQUEST_URL,
373
+ e
374
+ )
375
+ );
376
+ return;
377
+ }
362
378
 
363
- int expressInInt;
364
- try {
365
- expressInInt = Integer.parseInt(expiresIn);
366
- } catch (Exception e) {
367
- completer.setException(
368
- new RuntimeException(
369
- String.format(
370
- "Invalid response from %s. expires_in: %s is not a valid int. Error: %s",
371
- TOKEN_REQUEST_URL,
372
- expiresIn,
373
- e
374
- )
375
- )
376
- );
377
- Log.e(
378
- LOG_TAG,
379
+ int expressInInt;
380
+ try {
381
+ expressInInt = Integer.parseInt(expiresIn);
382
+ } catch (Exception e) {
383
+ completer.setException(
384
+ new RuntimeException(
379
385
  String.format(
380
386
  "Invalid response from %s. expires_in: %s is not a valid int. Error: %s",
381
387
  TOKEN_REQUEST_URL,
382
388
  expiresIn,
383
389
  e
384
390
  )
385
- );
386
- return;
387
- }
388
-
389
- completer.set(expressInInt > 5);
391
+ )
392
+ );
393
+ Log.e(
394
+ LOG_TAG,
395
+ String.format(
396
+ "Invalid response from %s. expires_in: %s is not a valid int. Error: %s",
397
+ TOKEN_REQUEST_URL,
398
+ expiresIn,
399
+ e
400
+ )
401
+ );
402
+ return;
390
403
  }
404
+
405
+ completer.set(expressInInt > 5);
391
406
  }
392
- );
407
+ }
408
+ );
393
409
 
394
410
  return "AccessTokenIsValidOperationTag";
395
411
  });
@@ -586,7 +602,56 @@ public class GoogleProvider implements SocialProvider {
586
602
  .apply();
587
603
  }
588
604
 
589
- private ListenableFuture<AuthorizationResult> getAuthorizationResult(Boolean forceRefreshToken) {
605
+ private void clearAuthorizationSlot(int index, CallbackToFutureAdapter.Completer<AuthorizationResult> expectedCompleter) {
606
+ if (index < 0) {
607
+ return;
608
+ }
609
+ synchronized (this) {
610
+ if (index < futuresList.size()) {
611
+ CallbackToFutureAdapter.Completer<AuthorizationResult> current = futuresList.get(index);
612
+ if (expectedCompleter != null && current != expectedCompleter) {
613
+ return;
614
+ }
615
+ futuresList.set(index, null);
616
+ }
617
+ if (Objects.equals(pendingAuthorizationSlotIndex, index)) {
618
+ pendingAuthorizationSlotIndex = null;
619
+ }
620
+ }
621
+ }
622
+
623
+ private void finishWaitAndClearSlot(AuthorizationWaitContext waitContext) {
624
+ synchronized (this) {
625
+ waitContext.markFinished();
626
+ clearAuthorizationSlot(waitContext.slotIndex[0], waitContext.slotCompleter);
627
+ }
628
+ }
629
+
630
+ private AuthorizationResult awaitAuthorizationResult(ListenableFuture<AuthorizationResult> future, AuthorizationWaitContext waitContext)
631
+ throws ExecutionException, InterruptedException, TimeoutException {
632
+ long preLaunchDeadlineNanos = System.nanoTime() + TimeUnit.SECONDS.toNanos(GoogleAuthorizationDecision.AUTHORIZATION_WAIT_SECONDS);
633
+ while (true) {
634
+ if (waitContext.isConsentUiLaunched()) {
635
+ return future.get(GoogleAuthorizationDecision.AUTHORIZATION_CONSENT_WAIT_SECONDS, TimeUnit.SECONDS);
636
+ }
637
+ long remainingNanos = preLaunchDeadlineNanos - System.nanoTime();
638
+ if (remainingNanos <= 0) {
639
+ throw new TimeoutException(GoogleAuthorizationDecision.AUTHORIZATION_WAIT_TIMEOUT_MESSAGE);
640
+ }
641
+ long pollNanos = Math.min(remainingNanos, TimeUnit.SECONDS.toNanos(1));
642
+ try {
643
+ return future.get(pollNanos, TimeUnit.NANOSECONDS);
644
+ } catch (TimeoutException ignored) {
645
+ // Poll until authorize completes, consent UI launches, or pre-launch deadline.
646
+ }
647
+ }
648
+ }
649
+
650
+ private ListenableFuture<AuthorizationResult> getAuthorizationResult(
651
+ Boolean forceRefreshToken,
652
+ String googleAccountId,
653
+ AuthorizationWaitContext waitContext
654
+ ) {
590
655
  // Account account = new Account(credential.getId(), "com.google");
591
656
  // String scopesString = "oauth2:" + TextUtils.join(" ", this.scopes);
592
657
  // String token = GoogleAuthUtil.getToken(
@@ -612,7 +677,9 @@ public class GoogleProvider implements SocialProvider {
612
677
  scopes.add(new Scope(scope));
613
678
  }
614
679
  AuthorizationRequest.Builder authorizationRequestBuilder = AuthorizationRequest.builder().setRequestedScopes(scopes);
615
- // .requestOfflineAccess(this.clientId)
680
+ if (googleAccountId != null && !googleAccountId.isEmpty()) {
681
+ authorizationRequestBuilder.setAccount(new Account(googleAccountId, "com.google"));
682
+ }
616
683
 
617
684
  if (GoogleProvider.this.mode == GoogleProviderLoginType.OFFLINE) {
618
685
  authorizationRequestBuilder = authorizationRequestBuilder.requestOfflineAccess(this.clientId, forceRefreshToken);
@@ -623,6 +690,9 @@ public class GoogleProvider implements SocialProvider {
623
690
  Identity.getAuthorizationClient(context)
624
691
  .authorize(authorizationRequest)
625
692
  .addOnSuccessListener((authorizationResult) -> {
693
+ if (waitContext.isFinished()) {
694
+ return;
695
+ }
626
696
  if (authorizationResult.hasResolution()) {
627
697
  // Access needs to be granted by the user
628
698
  PendingIntent pendingIntent = authorizationResult.getPendingIntent();
@@ -632,38 +702,68 @@ public class GoogleProvider implements SocialProvider {
632
702
  return;
633
703
  }
634
704
 
635
- // Find an index to put the future into.
636
- int fututeIndex = -1;
637
- for (int i = 0; i < futuresList.size(); i++) {
638
- if (futuresList.get(i) == null) {
639
- fututeIndex = i;
640
- break;
641
- }
642
- }
643
-
644
- if (fututeIndex == -1) {
645
- completer.setException(new RuntimeException("Cannot find index for future"));
646
- Log.e(LOG_TAG, "Cannot find index for future. Too many login requests??");
705
+ if (!GoogleAuthorizationDecision.canRouteAuthorizationResolution(activity)) {
706
+ Log.e(LOG_TAG, "AuthorizationClient returned a resolution, but MainActivity cannot route onActivityResult");
707
+ completer.setException(
708
+ new RuntimeException(GoogleAuthorizationDecision.UNROUTABLE_AUTHORIZATION_RESOLUTION_MESSAGE)
709
+ );
647
710
  return;
648
711
  }
649
712
 
650
- futuresList.set(fututeIndex, completer);
713
+ synchronized (GoogleProvider.this) {
714
+ if (waitContext.isFinished()) {
715
+ return;
716
+ }
651
717
 
652
- try {
653
- activity.startIntentSenderForResult(
654
- pendingIntent.getIntentSender(),
655
- GoogleProvider.REQUEST_AUTHORIZE_GOOGLE_MIN + fututeIndex,
656
- null,
657
- 0,
658
- 0,
659
- 0,
660
- null
661
- );
662
- } catch (IntentSender.SendIntentException e) {
663
- Log.e(LOG_TAG, "Couldn't start Authorization UI: " + e.getLocalizedMessage());
664
- completer.setException(e);
718
+ int fututeIndex = -1;
719
+ for (int i = 0; i < futuresList.size(); i++) {
720
+ if (futuresList.get(i) == null) {
721
+ fututeIndex = i;
722
+ break;
723
+ }
724
+ }
725
+
726
+ if (fututeIndex == -1) {
727
+ completer.setException(new RuntimeException("Cannot find index for future"));
728
+ Log.e(LOG_TAG, "Cannot find index for future. Too many login requests??");
729
+ return;
730
+ }
731
+
732
+ futuresList.set(fututeIndex, completer);
733
+ waitContext.slotIndex[0] = fututeIndex;
734
+ waitContext.slotCompleter = completer;
735
+ pendingAuthorizationSlotIndex = fututeIndex;
736
+
737
+ if (waitContext.isFinished()) {
738
+ clearAuthorizationSlot(fututeIndex, completer);
739
+ waitContext.slotIndex[0] = -1;
740
+ waitContext.slotCompleter = null;
741
+ return;
742
+ }
743
+
744
+ try {
745
+ activity.startIntentSenderForResult(
746
+ pendingIntent.getIntentSender(),
747
+ GoogleProvider.REQUEST_AUTHORIZE_GOOGLE_MIN + fututeIndex,
748
+ null,
749
+ 0,
750
+ 0,
751
+ 0,
752
+ null
753
+ );
754
+ waitContext.markConsentUiLaunched();
755
+ } catch (IntentSender.SendIntentException e) {
756
+ Log.e(LOG_TAG, "Couldn't start Authorization UI: " + e.getLocalizedMessage());
757
+ clearAuthorizationSlot(fututeIndex, completer);
758
+ waitContext.slotIndex[0] = -1;
759
+ waitContext.slotCompleter = null;
760
+ completer.setException(e);
761
+ }
665
762
  }
666
763
  } else {
764
+ if (waitContext.isFinished()) {
765
+ return;
766
+ }
667
767
  // Access already granted, continue with user action.
668
768
  // Online mode: a null access token is allowed (ID-token auth still succeeds).
669
769
  // Offline mode still requires serverAuthCode.
@@ -680,6 +780,9 @@ public class GoogleProvider implements SocialProvider {
680
780
  }
681
781
  })
682
782
  .addOnFailureListener((e) -> {
783
+ if (waitContext.isFinished()) {
784
+ return;
785
+ }
683
786
  completer.setException(new RuntimeException("Failed to authorize"));
684
787
  Log.e(LOG_TAG, "Failed to authorize", e);
685
788
  });
@@ -710,8 +813,25 @@ public class GoogleProvider implements SocialProvider {
710
813
 
711
814
  GoogleIdTokenCredential googleIdTokenCredential = GoogleIdTokenCredential.createFrom(credential.getData());
712
815
  String idToken = googleIdTokenCredential.getIdToken();
816
+ String googleAccountId = googleIdTokenCredential.getId();
817
+
818
+ if (
819
+ GoogleAuthorizationDecision.shouldSkipAuthorizationAfterCredentialSignIn(
820
+ GoogleProvider.this.mode,
821
+ GoogleProvider.this.scopes,
822
+ GoogleProvider.this.skipAuthOnlyAuthorizationAfterSignIn
823
+ )
824
+ ) {
825
+ resolveOnlineLogin(call, response, resultObj, user, idToken, null);
826
+ return;
827
+ }
713
828
 
714
- ListenableFuture<AuthorizationResult> future = getAuthorizationResult(forceRefreshToken);
829
+ AuthorizationWaitContext authorizationWaitContext = new AuthorizationWaitContext();
830
+ ListenableFuture<AuthorizationResult> future = getAuthorizationResult(
831
+ forceRefreshToken,
832
+ googleAccountId,
833
+ authorizationWaitContext
834
+ );
715
835
 
716
836
  // Use ExecutorService to retrieve the access token
717
837
  ExecutorService executor = Executors.newSingleThreadExecutor();
@@ -721,7 +841,7 @@ public class GoogleProvider implements SocialProvider {
721
841
  @Override
722
842
  public void run() {
723
843
  try {
724
- AuthorizationResult authResult = future.get();
844
+ AuthorizationResult authResult = awaitAuthorizationResult(future, authorizationWaitContext);
725
845
  if (GoogleProvider.this.mode == GoogleProviderLoginType.ONLINE) {
726
846
  // accessToken may be null: Credential Manager auth still succeeded.
727
847
  resolveOnlineLogin(call, response, resultObj, user, idToken, authResult.getAccessToken());
@@ -735,13 +855,24 @@ public class GoogleProvider implements SocialProvider {
735
855
  call.reject("Failed to get serverAuthCode");
736
856
  }
737
857
  }
858
+ } catch (TimeoutException e) {
859
+ finishWaitAndClearSlot(authorizationWaitContext);
860
+ String timeoutMessage = authorizationWaitContext.isConsentUiLaunched()
861
+ ? GoogleAuthorizationDecision.AUTHORIZATION_CONSENT_WAIT_TIMEOUT_MESSAGE
862
+ : GoogleAuthorizationDecision.AUTHORIZATION_WAIT_TIMEOUT_MESSAGE;
863
+ call.reject(timeoutMessage);
738
864
  } catch (Exception e) {
865
+ finishWaitAndClearSlot(authorizationWaitContext);
866
+ if (GoogleAuthorizationDecision.isUnroutableAuthorizationResolutionFailure(e)) {
867
+ call.reject(GoogleAuthorizationDecision.UNROUTABLE_AUTHORIZATION_RESOLUTION_MESSAGE);
868
+ return;
869
+ }
739
870
  // AuthorizationClient failed after Credential Manager returned a valid ID token.
740
871
  // For authentication-only online scopes, resolve with idToken + profile.
741
872
  if (
742
873
  GoogleProvider.this.mode == GoogleProviderLoginType.ONLINE &&
743
874
  idToken != null &&
744
- isAuthenticationOnlyScopes(GoogleProvider.this.scopes)
875
+ GoogleAuthorizationDecision.isAuthenticationOnlyScopes(GoogleProvider.this.scopes)
745
876
  ) {
746
877
  Log.w(
747
878
  LOG_TAG,
@@ -772,21 +903,28 @@ public class GoogleProvider implements SocialProvider {
772
903
 
773
904
  public void handleAuthorizationIntent(int requestCode, Intent data) {
774
905
  int futureIndex = requestCode - GoogleProvider.REQUEST_AUTHORIZE_GOOGLE_MIN;
775
- if (futureIndex < 0 || futureIndex >= futuresList.size()) {
776
- Log.e(
777
- LOG_TAG,
778
- String.format(
779
- "Invalid future index. REQUEST_AUTHORIZE_GOOGLE_MIN: %d, requestCode: %d, futures list length: %d, futureIndex: %d",
780
- REQUEST_AUTHORIZE_GOOGLE_MIN,
781
- requestCode,
782
- futuresList.size(),
783
- futureIndex
784
- )
785
- );
786
- return;
787
- }
906
+ CallbackToFutureAdapter.Completer<AuthorizationResult> future;
907
+ synchronized (this) {
908
+ if (futureIndex < 0 || futureIndex >= futuresList.size()) {
909
+ Log.e(
910
+ LOG_TAG,
911
+ String.format(
912
+ "Invalid future index. REQUEST_AUTHORIZE_GOOGLE_MIN: %d, requestCode: %d, futures list length: %d, futureIndex: %d",
913
+ REQUEST_AUTHORIZE_GOOGLE_MIN,
914
+ requestCode,
915
+ futuresList.size(),
916
+ futureIndex
917
+ )
918
+ );
919
+ return;
920
+ }
788
921
 
789
- CallbackToFutureAdapter.Completer<AuthorizationResult> future = futuresList.get(futureIndex);
922
+ future = futuresList.get(futureIndex);
923
+ if (future == null) {
924
+ Log.w(LOG_TAG, "Authorization result arrived after the login request ended");
925
+ return;
926
+ }
927
+ }
790
928
 
791
929
  try {
792
930
  AuthorizationResult authorizationResult = Identity.getAuthorizationClient(this.activity).getAuthorizationResultFromIntent(data);
@@ -794,6 +932,8 @@ public class GoogleProvider implements SocialProvider {
794
932
  } catch (ApiException e) {
795
933
  Log.e(LOG_TAG, "Cannot get getAuthorizationResultFromIntent", e);
796
934
  future.setException(new RuntimeException("Cannot get getAuthorizationResultFromIntent"));
935
+ } finally {
936
+ clearAuthorizationSlot(futureIndex, future);
797
937
  }
798
938
  }
799
939
 
@@ -1375,7 +1515,25 @@ public class GoogleProvider implements SocialProvider {
1375
1515
  );
1376
1516
  String newIdToken = googleIdTokenCredential.getIdToken();
1377
1517
 
1378
- ListenableFuture<AuthorizationResult> future = getAuthorizationResult(false);
1518
+ if (
1519
+ GoogleAuthorizationDecision.shouldSkipAuthorizationAfterCredentialSignIn(
1520
+ GoogleProvider.this.mode,
1521
+ GoogleProvider.this.scopes,
1522
+ GoogleProvider.this.skipAuthOnlyAuthorizationAfterSignIn
1523
+ )
1524
+ ) {
1525
+ persistState(newIdToken, null, GoogleProvider.this.scopes);
1526
+ call.resolve();
1527
+ return;
1528
+ }
1529
+
1530
+ String googleAccountId = googleIdTokenCredential.getId();
1531
+ AuthorizationWaitContext authorizationWaitContext = new AuthorizationWaitContext();
1532
+ ListenableFuture<AuthorizationResult> future = getAuthorizationResult(
1533
+ false,
1534
+ googleAccountId,
1535
+ authorizationWaitContext
1536
+ );
1379
1537
 
1380
1538
  ExecutorService authExecutor = Executors.newSingleThreadExecutor();
1381
1539
  authExecutor.execute(
@@ -1383,7 +1541,7 @@ public class GoogleProvider implements SocialProvider {
1383
1541
  @Override
1384
1542
  public void run() {
1385
1543
  try {
1386
- AuthorizationResult authResult = future.get(60, TimeUnit.SECONDS);
1544
+ AuthorizationResult authResult = awaitAuthorizationResult(future, authorizationWaitContext);
1387
1545
  String newAccessToken = authResult.getAccessToken();
1388
1546
  // Persist ID token even when access token is unavailable.
1389
1547
  persistState(
@@ -1392,8 +1550,19 @@ public class GoogleProvider implements SocialProvider {
1392
1550
  GoogleProvider.this.scopes
1393
1551
  );
1394
1552
  call.resolve();
1553
+ } catch (TimeoutException e) {
1554
+ finishWaitAndClearSlot(authorizationWaitContext);
1555
+ String timeoutMessage = authorizationWaitContext.isConsentUiLaunched()
1556
+ ? GoogleAuthorizationDecision.AUTHORIZATION_CONSENT_WAIT_TIMEOUT_MESSAGE
1557
+ : GoogleAuthorizationDecision.AUTHORIZATION_WAIT_TIMEOUT_MESSAGE;
1558
+ call.reject(timeoutMessage);
1395
1559
  } catch (Exception e) {
1396
- if (isAuthenticationOnlyScopes(GoogleProvider.this.scopes)) {
1560
+ finishWaitAndClearSlot(authorizationWaitContext);
1561
+ if (GoogleAuthorizationDecision.isUnroutableAuthorizationResolutionFailure(e)) {
1562
+ call.reject(GoogleAuthorizationDecision.UNROUTABLE_AUTHORIZATION_RESOLUTION_MESSAGE);
1563
+ return;
1564
+ }
1565
+ if (GoogleAuthorizationDecision.isAuthenticationOnlyScopes(GoogleProvider.this.scopes)) {
1397
1566
  try {
1398
1567
  // Authorization failed; still keep the refreshed ID token.
1399
1568
  persistState(newIdToken, null, GoogleProvider.this.scopes);