capacitor-auth-manager 2.4.4 → 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.
Files changed (86) hide show
  1. package/AI-INTEGRATION-GUIDE.md +176 -0
  2. package/CHANGELOG.md +143 -0
  3. package/CapacitorAuthManager.podspec +3 -3
  4. package/README.md +99 -76
  5. package/android/build.gradle +23 -25
  6. package/android/consumer-rules.pro +14 -0
  7. package/android/proguard-rules.pro +5 -30
  8. package/android/src/main/AndroidManifest.xml +4 -9
  9. package/android/src/main/java/com/aoneahsan/capacitor_auth_manager/ActivityLauncher.java +26 -0
  10. package/android/src/main/java/com/aoneahsan/capacitor_auth_manager/AuthErrorCodes.java +32 -0
  11. package/android/src/main/java/com/aoneahsan/capacitor_auth_manager/AuthException.java +34 -0
  12. package/android/src/main/java/com/aoneahsan/capacitor_auth_manager/AuthStorage.java +46 -25
  13. package/android/src/main/java/com/aoneahsan/capacitor_auth_manager/CapacitorAuthManager.java +62 -40
  14. package/android/src/main/java/com/aoneahsan/capacitor_auth_manager/CapacitorAuthManagerPlugin.java +124 -66
  15. package/android/src/main/java/com/aoneahsan/capacitor_auth_manager/GoogleAuthProvider.java +225 -374
  16. package/android/src/main/java/com/aoneahsan/capacitor_auth_manager/GoogleCredentialManagerSignIn.java +175 -0
  17. package/android/src/main/java/com/aoneahsan/capacitor_auth_manager/GoogleLegacySignIn.java +133 -0
  18. package/android/src/main/java/com/aoneahsan/capacitor_auth_manager/GoogleProfileCallback.java +8 -0
  19. package/android/src/main/java/com/aoneahsan/capacitor_auth_manager/GoogleResultMapper.java +158 -0
  20. package/android/src/main/java/com/aoneahsan/capacitor_auth_manager/ProviderFactory.java +11 -3
  21. package/android/src/main/java/com/aoneahsan/capacitor_auth_manager/SigningDiagnostics.java +76 -0
  22. package/dist/angular.cjs.js +421 -3376
  23. package/dist/core.cjs.js +589 -149
  24. package/dist/esm/angular/auth.guard.d.ts +1 -1
  25. package/dist/esm/angular/auth.module.d.ts +1 -1
  26. package/dist/esm/angular/auth.module.js +1 -1
  27. package/dist/esm/angular/auth.service.d.ts +2 -2
  28. package/dist/esm/angular/auth.service.js +1 -1
  29. package/dist/esm/angular/index.d.ts +4 -4
  30. package/dist/esm/angular/index.js +4 -4
  31. package/dist/esm/capacitor-plugin.d.ts +2 -3
  32. package/dist/esm/capacitor-plugin.js +14 -4
  33. package/dist/esm/core/auth-manager.d.ts +20 -2
  34. package/dist/esm/core/auth-manager.js +68 -12
  35. package/dist/esm/core/index.d.ts +5 -4
  36. package/dist/esm/core/index.js +5 -4
  37. package/dist/esm/core/provider-manifests.d.ts +1 -1
  38. package/dist/esm/core/provider-manifests.js +12 -13
  39. package/dist/esm/core/provider-registry.d.ts +8 -5
  40. package/dist/esm/core/provider-registry.js +41 -10
  41. package/dist/esm/core/types.d.ts +2 -2
  42. package/dist/esm/definitions.d.ts +29 -0
  43. package/dist/esm/index.d.ts +12 -12
  44. package/dist/esm/index.js +7 -7
  45. package/dist/esm/package.json +1 -0
  46. package/dist/esm/providers/base-provider.d.ts +7 -8
  47. package/dist/esm/providers/base-provider.js +7 -8
  48. package/dist/esm/providers/native/google-native-provider.d.ts +13 -2
  49. package/dist/esm/providers/native/google-native-provider.js +50 -6
  50. package/dist/esm/providers/oauth-provider.d.ts +2 -2
  51. package/dist/esm/providers/oauth-provider.js +3 -3
  52. package/dist/esm/providers/provider-factory.d.ts +5 -5
  53. package/dist/esm/providers/provider-factory.js +2 -2
  54. package/dist/esm/providers/web/google-provider.d.ts +74 -18
  55. package/dist/esm/providers/web/google-provider.js +391 -117
  56. package/dist/esm/providers/web/index.d.ts +1 -1
  57. package/dist/esm/providers/web/index.js +1 -1
  58. package/dist/esm/react/hooks.d.ts +2 -2
  59. package/dist/esm/react/hooks.js +2 -2
  60. package/dist/esm/react/index.d.ts +3 -3
  61. package/dist/esm/react/index.js +3 -3
  62. package/dist/esm/react/types.d.ts +1 -1
  63. package/dist/esm/utils/auth-error.d.ts +1 -1
  64. package/dist/esm/utils/auth-error.js +1 -1
  65. package/dist/esm/utils/event-emitter.d.ts +1 -1
  66. package/dist/esm/utils/event-emitter.js +1 -1
  67. package/dist/esm/utils/pending-verification-store.js +1 -1
  68. package/dist/esm/utils/storage.d.ts +2 -2
  69. package/dist/esm/utils/storage.js +31 -7
  70. package/dist/esm/vue/composables.d.ts +2 -2
  71. package/dist/esm/vue/composables.js +1 -1
  72. package/dist/esm/vue/index.d.ts +2 -2
  73. package/dist/esm/vue/index.js +2 -2
  74. package/dist/esm/web.d.ts +1 -1
  75. package/dist/esm/web.js +6 -6
  76. package/dist/plugin.cjs.js +291 -2771
  77. package/dist/plugin.js +585 -147
  78. package/dist/providers-web.cjs.js +1317 -0
  79. package/dist/react.cjs.js +310 -3265
  80. package/dist/vue.cjs.js +266 -3221
  81. package/ios/Plugin/AuthStorage.swift +3 -1
  82. package/ios/Plugin/GoogleAuthProvider.swift +7 -4
  83. package/ios/Plugin/Models.swift +28 -0
  84. package/ios/Plugin/Plugin.swift +64 -40
  85. package/package.json +54 -32
  86. package/scripts/configure.js +71 -325
@@ -0,0 +1,175 @@
1
+ package com.aoneahsan.capacitor_auth_manager;
2
+
3
+ import android.app.Activity;
4
+ import android.content.Context;
5
+ import android.net.Uri;
6
+
7
+ import androidx.core.content.ContextCompat;
8
+ import androidx.credentials.ClearCredentialStateRequest;
9
+ import androidx.credentials.Credential;
10
+ import androidx.credentials.CredentialManager;
11
+ import androidx.credentials.CredentialManagerCallback;
12
+ import androidx.credentials.CustomCredential;
13
+ import androidx.credentials.GetCredentialRequest;
14
+ import androidx.credentials.GetCredentialResponse;
15
+ import androidx.credentials.exceptions.ClearCredentialException;
16
+ import androidx.credentials.exceptions.GetCredentialCancellationException;
17
+ import androidx.credentials.exceptions.GetCredentialException;
18
+ import androidx.credentials.exceptions.GetCredentialInterruptedException;
19
+ import androidx.credentials.exceptions.NoCredentialException;
20
+
21
+ import com.google.android.libraries.identity.googleid.GetGoogleIdOption;
22
+ import com.google.android.libraries.identity.googleid.GetSignInWithGoogleOption;
23
+ import com.google.android.libraries.identity.googleid.GoogleIdTokenCredential;
24
+
25
+ /**
26
+ * The Android Credential Manager Google path ({@code androidx.credentials} + Google Identity): the
27
+ * bottom sheet ({@link GetGoogleIdOption}) and the "Sign in with Google" button
28
+ * ({@link GetSignInWithGoogleOption}). Every failure keeps Google's own exception class and message.
29
+ */
30
+ final class GoogleCredentialManagerSignIn {
31
+
32
+ /** Raised when the bottom sheet offers no account, so the caller can try the button flow. */
33
+ static final class NoGoogleCredentialException extends AuthException {
34
+ NoGoogleCredentialException(String message, Throwable cause) {
35
+ super(AuthErrorCodes.SIGN_IN_FAILED, message, cause);
36
+ }
37
+ }
38
+
39
+ private final Context context;
40
+ private final Activity activity;
41
+ private final AuthLogger logger;
42
+
43
+ GoogleCredentialManagerSignIn(Context context, Activity activity, AuthLogger logger) {
44
+ this.context = context;
45
+ this.activity = activity;
46
+ this.logger = logger;
47
+ }
48
+
49
+ void requestBottomSheet(String serverClientId, String nonce, boolean filterByAuthorized, boolean autoSelect,
50
+ GoogleProfileCallback callback) {
51
+ try {
52
+ GetGoogleIdOption.Builder option = new GetGoogleIdOption.Builder()
53
+ .setServerClientId(serverClientId)
54
+ .setFilterByAuthorizedAccounts(filterByAuthorized)
55
+ .setAutoSelectEnabled(autoSelect);
56
+ if (nonce != null && !nonce.isEmpty()) {
57
+ option.setNonce(nonce);
58
+ }
59
+ launch(new GetCredentialRequest.Builder().addCredentialOption(option.build()).build(), callback);
60
+ } catch (Exception e) {
61
+ logger.error("Failed to start Google Credential Manager request", e);
62
+ callback.onError(new AuthException(AuthErrorCodes.SIGN_IN_FAILED,
63
+ "Failed to start Google sign-in: " + describe(e), e));
64
+ }
65
+ }
66
+
67
+ void requestButton(String serverClientId, String nonce, String hostedDomain, GoogleProfileCallback callback) {
68
+ try {
69
+ GetSignInWithGoogleOption.Builder option = new GetSignInWithGoogleOption.Builder(serverClientId);
70
+ if (nonce != null && !nonce.isEmpty()) {
71
+ option.setNonce(nonce);
72
+ }
73
+ if (hostedDomain != null && !hostedDomain.isEmpty()) {
74
+ option.setHostedDomainFilter(hostedDomain);
75
+ }
76
+ launch(new GetCredentialRequest.Builder().addCredentialOption(option.build()).build(), callback);
77
+ } catch (Exception e) {
78
+ logger.error("Failed to start the Sign in with Google button flow", e);
79
+ callback.onError(new AuthException(AuthErrorCodes.SIGN_IN_FAILED,
80
+ "Failed to start the Sign in with Google button flow: " + describe(e), e));
81
+ }
82
+ }
83
+
84
+ /** Clears Credential Manager's selected-account state; {@code done} runs whatever the outcome. */
85
+ void clearState(Runnable done) {
86
+ try {
87
+ CredentialManager.create(context).clearCredentialStateAsync(
88
+ new ClearCredentialStateRequest(), null, ContextCompat.getMainExecutor(context),
89
+ new CredentialManagerCallback<Void, ClearCredentialException>() {
90
+ @Override
91
+ public void onResult(Void unused) {
92
+ done.run();
93
+ }
94
+
95
+ @Override
96
+ public void onError(ClearCredentialException e) {
97
+ logger.error("Failed to clear Credential Manager state", e);
98
+ done.run();
99
+ }
100
+ });
101
+ } catch (Exception e) {
102
+ logger.error("Error clearing Credential Manager state", e);
103
+ done.run();
104
+ }
105
+ }
106
+
107
+ private void launch(GetCredentialRequest request, final GoogleProfileCallback callback) {
108
+ if (activity == null) {
109
+ callback.onError(new AuthException(AuthErrorCodes.PROVIDER_NOT_INITIALIZED,
110
+ "Google sign-in requires a foreground Activity."));
111
+ return;
112
+ }
113
+ CredentialManager.create(context).getCredentialAsync(activity, request, null, ContextCompat.getMainExecutor(context),
114
+ new CredentialManagerCallback<GetCredentialResponse, GetCredentialException>() {
115
+ @Override
116
+ public void onResult(GetCredentialResponse response) {
117
+ handleResponse(response, callback);
118
+ }
119
+
120
+ @Override
121
+ public void onError(GetCredentialException e) {
122
+ callback.onError(mapError(e));
123
+ }
124
+ });
125
+ }
126
+
127
+ private void handleResponse(GetCredentialResponse response, GoogleProfileCallback callback) {
128
+ try {
129
+ Credential credential = response.getCredential();
130
+ if (credential instanceof CustomCredential
131
+ && GoogleIdTokenCredential.TYPE_GOOGLE_ID_TOKEN_CREDENTIAL.equals(credential.getType())) {
132
+ GoogleIdTokenCredential google = GoogleIdTokenCredential.createFrom(((CustomCredential) credential).getData());
133
+ Uri photo = google.getProfilePictureUri();
134
+ logger.info("Google sign-in successful (Credential Manager)");
135
+ callback.onSuccess(new GoogleResultMapper.Profile(google.getIdToken(), google.getId(),
136
+ google.getDisplayName(), photo != null ? photo.toString() : null, null, null));
137
+ } else {
138
+ String type = credential != null ? credential.getType() : "null";
139
+ logger.error("Unexpected credential type from Credential Manager: " + type, null);
140
+ callback.onError(new AuthException(AuthErrorCodes.INVALID_CREDENTIALS,
141
+ "Unexpected credential type returned from Google sign-in: " + type));
142
+ }
143
+ } catch (Exception e) {
144
+ logger.error("Unexpected error handling Google credential", e);
145
+ callback.onError(new AuthException(AuthErrorCodes.INVALID_CREDENTIALS,
146
+ "Could not read the Google credential: " + describe(e), e));
147
+ }
148
+ }
149
+
150
+ /** Keeps Google's own class + message ({@code [28444] …}) and names the package + signing SHA-1. */
151
+ private AuthException mapError(GetCredentialException e) {
152
+ if (e instanceof GetCredentialCancellationException) {
153
+ logger.info("Google sign-in cancelled by user");
154
+ return new AuthException(AuthErrorCodes.USER_CANCELLED, "User cancelled Google sign-in", e);
155
+ }
156
+ if (e instanceof GetCredentialInterruptedException) {
157
+ logger.warn("Google sign-in interrupted: " + describe(e));
158
+ return new AuthException(AuthErrorCodes.NETWORK_ERROR,
159
+ "Google sign-in was interrupted (" + describe(e) + "). Try again.", e);
160
+ }
161
+ if (e instanceof NoCredentialException) {
162
+ logger.warn("No Google credential offered: " + describe(e));
163
+ return new NoGoogleCredentialException("No Google account was offered (" + describe(e) + "; "
164
+ + SigningDiagnostics.describe(context) + "). Check a Google account is on the device and an "
165
+ + "Android OAuth client exists for this package + SHA-1 in the serverClientId's Google Cloud project.", e);
166
+ }
167
+ logger.error("Google sign-in failed: " + describe(e), e);
168
+ return new AuthException(AuthErrorCodes.SIGN_IN_FAILED,
169
+ "Google sign-in failed (" + describe(e) + "; " + SigningDiagnostics.describe(context) + ")", e);
170
+ }
171
+
172
+ private static String describe(Exception e) {
173
+ return e.getClass().getSimpleName() + ": " + e.getMessage();
174
+ }
175
+ }
@@ -0,0 +1,133 @@
1
+ package com.aoneahsan.capacitor_auth_manager;
2
+
3
+ import android.app.Activity;
4
+ import android.content.Context;
5
+ import android.content.Intent;
6
+
7
+ import com.google.android.gms.auth.api.signin.GoogleSignIn;
8
+ import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
9
+ import com.google.android.gms.auth.api.signin.GoogleSignInClient;
10
+ import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
11
+ import com.google.android.gms.auth.api.signin.GoogleSignInStatusCodes;
12
+ import com.google.android.gms.common.api.ApiException;
13
+ import com.google.android.gms.common.api.CommonStatusCodes;
14
+ import com.google.android.gms.tasks.Task;
15
+
16
+ /**
17
+ * The legacy {@code GoogleSignIn} flow — the API {@code @codetrix-studio/capacitor-google-auth} used —
18
+ * kept as the automatic fallback when Credential Manager refuses a request.
19
+ *
20
+ * <p>Google deprecated it and play-services-auth 22.0.0 removed it, so this ships on the pinned 21.x
21
+ * line (see {@code android/build.gradle}). The Activity result arrives through {@link ActivityLauncher},
22
+ * that is through Capacitor's {@code @ActivityCallback}, never through an un-forwarded
23
+ * {@code onActivityResult}.</p>
24
+ */
25
+ final class GoogleLegacySignIn {
26
+
27
+ private final Context context;
28
+ private final Activity activity;
29
+ private final AuthLogger logger;
30
+
31
+ GoogleLegacySignIn(Context context, Activity activity, AuthLogger logger) {
32
+ this.context = context;
33
+ this.activity = activity;
34
+ this.logger = logger;
35
+ }
36
+
37
+ /** Interactive sign-in: shows Google's account chooser. */
38
+ void signIn(String serverClientId, String hostedDomain, String loginHint, ActivityLauncher launcher, final GoogleProfileCallback callback) {
39
+ if (launcher == null || activity == null) {
40
+ callback.onError(new AuthException(AuthErrorCodes.PROVIDER_NOT_INITIALIZED,
41
+ "Legacy Google Sign-In needs a foreground Activity and an active plugin call."));
42
+ return;
43
+ }
44
+ GoogleSignInClient client = client(serverClientId, hostedDomain, loginHint);
45
+ Intent intent = client.getSignInIntent();
46
+ logger.info("Starting legacy Google Sign-In (account chooser)");
47
+ boolean launched = launcher.launch(intent, (resultCode, data) ->
48
+ handleTask(GoogleSignIn.getSignedInAccountFromIntent(data), callback));
49
+ if (!launched) {
50
+ callback.onError(new AuthException(AuthErrorCodes.INTERNAL_ERROR,
51
+ "Legacy Google Sign-In could not start: no plugin call is in flight."));
52
+ }
53
+ }
54
+
55
+ /** Silent sign-in for a returning user; never shows UI. */
56
+ void silentSignIn(String serverClientId, final GoogleProfileCallback callback) {
57
+ try {
58
+ client(serverClientId, null, null).silentSignIn()
59
+ .addOnCompleteListener(task -> handleTask(task, callback));
60
+ } catch (Exception e) {
61
+ callback.onError(new AuthException(AuthErrorCodes.NO_AUTH_SESSION,
62
+ "Legacy silent Google Sign-In failed: " + e.getMessage(), e));
63
+ }
64
+ }
65
+
66
+ /** Clears the legacy cached account so the next interactive sign-in shows the chooser. */
67
+ void signOut() {
68
+ try {
69
+ GoogleSignIn.getClient(context, new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).build()).signOut();
70
+ } catch (Exception e) {
71
+ logger.warn("Legacy Google sign-out failed: " + e.getMessage());
72
+ }
73
+ }
74
+
75
+ private GoogleSignInClient client(String serverClientId, String hostedDomain, String loginHint) {
76
+ GoogleSignInOptions.Builder builder = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
77
+ .requestIdToken(serverClientId)
78
+ .requestEmail()
79
+ .requestProfile();
80
+ if (hostedDomain != null && !hostedDomain.isEmpty()) {
81
+ builder.setHostedDomain(hostedDomain);
82
+ }
83
+ if (loginHint != null && !loginHint.isEmpty()) {
84
+ builder.setAccountName(loginHint);
85
+ }
86
+ return activity != null
87
+ ? GoogleSignIn.getClient(activity, builder.build())
88
+ : GoogleSignIn.getClient(context, builder.build());
89
+ }
90
+
91
+ private void handleTask(Task<GoogleSignInAccount> task, GoogleProfileCallback callback) {
92
+ try {
93
+ GoogleSignInAccount account = task.getResult(ApiException.class);
94
+ if (account == null || account.getIdToken() == null || account.getIdToken().isEmpty()) {
95
+ callback.onError(new AuthException(AuthErrorCodes.SIGN_IN_FAILED,
96
+ "Legacy Google Sign-In returned no ID token. Check that serverClientId is the WEB "
97
+ + "OAuth client id (" + SigningDiagnostics.describe(context) + ")."));
98
+ return;
99
+ }
100
+ String photo = account.getPhotoUrl() != null ? account.getPhotoUrl().toString() : null;
101
+ logger.info("Legacy Google Sign-In successful");
102
+ callback.onSuccess(new GoogleResultMapper.Profile(account.getIdToken(), account.getEmail(),
103
+ account.getDisplayName(), photo, account.getId(), account.getServerAuthCode()));
104
+ } catch (ApiException e) {
105
+ callback.onError(mapApiException(e));
106
+ } catch (Exception e) {
107
+ callback.onError(new AuthException(AuthErrorCodes.SIGN_IN_FAILED,
108
+ "Legacy Google Sign-In failed: " + e.getMessage(), e));
109
+ }
110
+ }
111
+
112
+ private AuthException mapApiException(ApiException e) {
113
+ int status = e.getStatusCode();
114
+ String detail = "Legacy Google Sign-In status " + status + " ("
115
+ + GoogleSignInStatusCodes.getStatusCodeString(status) + ")";
116
+ if (status == GoogleSignInStatusCodes.SIGN_IN_CANCELLED) {
117
+ return new AuthException(AuthErrorCodes.USER_CANCELLED, "User cancelled Google sign-in", e);
118
+ }
119
+ if (status == CommonStatusCodes.NETWORK_ERROR) {
120
+ return new AuthException(AuthErrorCodes.NETWORK_ERROR, detail + ". Check the connection and try again.", e);
121
+ }
122
+ if (status == CommonStatusCodes.DEVELOPER_ERROR) {
123
+ return new AuthException(AuthErrorCodes.MISSING_CONFIGURATION, detail
124
+ + ": Google has no Android OAuth client for this app's package + signing certificate in the "
125
+ + "same Google Cloud project as serverClientId. Register this SHA-1 (" + SigningDiagnostics.describe(context)
126
+ + "). A Play-installed build is signed with the Play App Signing key.", e);
127
+ }
128
+ if (status == CommonStatusCodes.SIGN_IN_REQUIRED) {
129
+ return new AuthException(AuthErrorCodes.NO_AUTH_SESSION, detail, e);
130
+ }
131
+ return new AuthException(AuthErrorCodes.SIGN_IN_FAILED, detail + ": " + e.getMessage(), e);
132
+ }
133
+ }
@@ -0,0 +1,8 @@
1
+ package com.aoneahsan.capacitor_auth_manager;
2
+
3
+ /** Result of one Android Google sign-in path: the signed-in profile, or a coded failure. */
4
+ interface GoogleProfileCallback {
5
+ void onSuccess(GoogleResultMapper.Profile profile);
6
+
7
+ void onError(AuthException error);
8
+ }
@@ -0,0 +1,158 @@
1
+ package com.aoneahsan.capacitor_auth_manager;
2
+
3
+ import android.util.Base64;
4
+
5
+ import com.getcapacitor.JSObject;
6
+
7
+ import org.json.JSONArray;
8
+ import org.json.JSONObject;
9
+
10
+ import java.nio.charset.StandardCharsets;
11
+ import java.text.SimpleDateFormat;
12
+ import java.util.Date;
13
+ import java.util.Locale;
14
+ import java.util.TimeZone;
15
+
16
+ /**
17
+ * Builds the Firebase-agnostic sign-in result shared by both Android Google paths — Credential
18
+ * Manager and the legacy GoogleSignIn fallback — so JS receives one shape whichever path ran.
19
+ */
20
+ final class GoogleResultMapper {
21
+ static final String PROVIDER_ID = "google.com";
22
+
23
+ private GoogleResultMapper() {
24
+ }
25
+
26
+ /** Profile fields as each path exposes them; any may be {@code null}. */
27
+ static final class Profile {
28
+ final String idToken;
29
+ final String email;
30
+ final String displayName;
31
+ final String photoURL;
32
+ /** The Google account id ({@code sub}) when the path exposes it directly. */
33
+ final String googleId;
34
+ final String serverAuthCode;
35
+
36
+ Profile(String idToken, String email, String displayName, String photoURL, String googleId, String serverAuthCode) {
37
+ this.idToken = idToken;
38
+ this.email = email;
39
+ this.displayName = displayName;
40
+ this.photoURL = photoURL;
41
+ this.googleId = googleId;
42
+ this.serverAuthCode = serverAuthCode;
43
+ }
44
+ }
45
+
46
+ /** {@code { user, credential, additionalUserInfo, operationType }}. */
47
+ static JSObject buildResult(Profile profile, AuthLogger logger) {
48
+ JSONObject claims = parseIdTokenClaims(profile.idToken, logger);
49
+ JSObject result = new JSObject();
50
+ result.put("user", createUserObject(profile, claims));
51
+ result.put("credential", createCredentialObject(profile));
52
+
53
+ JSObject additionalUserInfo = new JSObject();
54
+ additionalUserInfo.put("isNewUser", false);
55
+ additionalUserInfo.put("providerId", PROVIDER_ID);
56
+ if (profile.email != null) {
57
+ additionalUserInfo.put("username", profile.email);
58
+ }
59
+ result.put("additionalUserInfo", additionalUserInfo);
60
+ result.put("operationType", "signIn");
61
+ return result;
62
+ }
63
+
64
+ private static JSObject createUserObject(Profile profile, JSONObject claims) {
65
+ String email = profile.email;
66
+ String displayName = profile.displayName;
67
+ String photoURL = profile.photoURL;
68
+ String uid = profile.googleId;
69
+ boolean emailVerified = true;
70
+ if (claims != null) {
71
+ String sub = claims.optString("sub", null);
72
+ if (sub != null && !sub.isEmpty()) {
73
+ uid = sub;
74
+ }
75
+ if (claims.has("email_verified")) {
76
+ emailVerified = claims.optBoolean("email_verified", true);
77
+ }
78
+ if (email == null) {
79
+ email = claims.optString("email", null);
80
+ }
81
+ if (displayName == null) {
82
+ displayName = claims.optString("name", null);
83
+ }
84
+ if (photoURL == null) {
85
+ String picture = claims.optString("picture", null);
86
+ if (picture != null && !picture.isEmpty()) {
87
+ photoURL = picture;
88
+ }
89
+ }
90
+ }
91
+ if (uid == null || uid.isEmpty()) {
92
+ uid = email;
93
+ }
94
+
95
+ JSObject user = new JSObject();
96
+ user.put("uid", uid);
97
+ user.put("email", email);
98
+ user.put("emailVerified", emailVerified);
99
+ user.put("displayName", displayName);
100
+ user.put("photoURL", photoURL);
101
+ user.put("phoneNumber", null); // Google ID tokens do not carry a phone number.
102
+ user.put("isAnonymous", false);
103
+
104
+ JSONArray providerData = new JSONArray();
105
+ JSObject providerEntry = new JSObject();
106
+ providerEntry.put("providerId", PROVIDER_ID);
107
+ providerEntry.put("uid", uid);
108
+ providerEntry.put("displayName", displayName);
109
+ providerEntry.put("email", email);
110
+ providerEntry.put("phoneNumber", null);
111
+ providerEntry.put("photoURL", photoURL);
112
+ providerData.put(providerEntry);
113
+ user.put("providerData", providerData);
114
+
115
+ JSObject metadata = new JSObject();
116
+ SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US);
117
+ sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
118
+ metadata.put("lastSignInTime", sdf.format(new Date()));
119
+ user.put("metadata", metadata);
120
+ return user;
121
+ }
122
+
123
+ private static JSObject createCredentialObject(Profile profile) {
124
+ JSObject credential = new JSObject();
125
+ credential.put("providerId", PROVIDER_ID);
126
+ credential.put("signInMethod", PROVIDER_ID);
127
+ credential.put("idToken", profile.idToken);
128
+ if (profile.serverAuthCode != null) {
129
+ credential.put("serverAuthCode", profile.serverAuthCode);
130
+ }
131
+ // No accessToken on either Android path: consumers feed credential.idToken into their own
132
+ // signInWithCredential / signInWithIdToken.
133
+ return credential;
134
+ }
135
+
136
+ /**
137
+ * Best-effort decode of the (unverified) ID-token payload to read {@code sub}, {@code email_verified}
138
+ * and {@code exp}. The signature is verified by the consumer's backend; this only enriches the result.
139
+ */
140
+ static JSONObject parseIdTokenClaims(String idToken, AuthLogger logger) {
141
+ if (idToken == null || idToken.isEmpty()) {
142
+ return null;
143
+ }
144
+ try {
145
+ String[] parts = idToken.split("\\.");
146
+ if (parts.length < 2) {
147
+ return null;
148
+ }
149
+ byte[] decoded = Base64.decode(parts[1], Base64.URL_SAFE | Base64.NO_PADDING | Base64.NO_WRAP);
150
+ return new JSONObject(new String(decoded, StandardCharsets.UTF_8));
151
+ } catch (Exception e) {
152
+ if (logger != null) {
153
+ logger.warn("Failed to parse Google ID token claims");
154
+ }
155
+ return null;
156
+ }
157
+ }
158
+ }
@@ -27,7 +27,8 @@ public class ProviderFactory {
27
27
  Activity activity,
28
28
  AuthStorage storage,
29
29
  AuthLogger logger,
30
- JSObject config
30
+ JSObject config,
31
+ ActivityLauncher activityLauncher
31
32
  ) {
32
33
  if (providerType == null) {
33
34
  return null;
@@ -36,7 +37,7 @@ public class ProviderFactory {
36
37
  switch (providerType.toLowerCase()) {
37
38
  case "google":
38
39
  case "google.com":
39
- return createGoogleProvider(context, activity, storage, logger, config);
40
+ return createGoogleProvider(context, activity, storage, logger, config, activityLauncher);
40
41
 
41
42
  default:
42
43
  // Every non-Google provider is disabled in the Google-first build. The JS layer already
@@ -51,9 +52,11 @@ public class ProviderFactory {
51
52
  Activity activity,
52
53
  AuthStorage storage,
53
54
  AuthLogger logger,
54
- JSObject config
55
+ JSObject config,
56
+ ActivityLauncher activityLauncher
55
57
  ) {
56
58
  GoogleAuthProvider provider = new GoogleAuthProvider(context, activity, storage, logger);
59
+ provider.setActivityLauncher(activityLauncher);
57
60
 
58
61
  if (config != null) {
59
62
  String clientId = config.getString("clientId");
@@ -89,6 +92,11 @@ public class ProviderFactory {
89
92
  provider.setLoginHint(loginHint);
90
93
  }
91
94
 
95
+ String androidFlow = config.getString("androidFlow");
96
+ if (androidFlow != null) {
97
+ provider.setAndroidFlow(androidFlow);
98
+ }
99
+
92
100
  try {
93
101
  JSONArray scopesArray = config.getJSONArray("scopes");
94
102
  if (scopesArray != null) {
@@ -0,0 +1,76 @@
1
+ package com.aoneahsan.capacitor_auth_manager;
2
+
3
+ import android.content.Context;
4
+ import android.content.pm.PackageInfo;
5
+ import android.content.pm.PackageManager;
6
+ import android.content.pm.Signature;
7
+ import android.os.Build;
8
+
9
+ import java.security.MessageDigest;
10
+ import java.util.ArrayList;
11
+ import java.util.List;
12
+
13
+ /**
14
+ * Describes how the running app is signed, for Google sign-in configuration errors.
15
+ *
16
+ * <p>Google matches an Android OAuth client by package name + signing-certificate SHA-1. A build
17
+ * installed from Google Play is re-signed with the <b>Play App Signing</b> key, so its SHA-1 differs
18
+ * from the upload key a locally signed APK carries. When that SHA-1 has no OAuth client, Credential
19
+ * Manager refuses the request before showing any account picker. Naming the installed SHA-1 in the
20
+ * error turns that silent mismatch into one value to register. Certificate fingerprints are public
21
+ * (they are readable from any installed APK), so including them is safe.</p>
22
+ */
23
+ final class SigningDiagnostics {
24
+
25
+ private SigningDiagnostics() {
26
+ }
27
+
28
+ /** {@code "package=com.example.app, signing SHA-1=AA:BB:…"}, or the package alone if unreadable. */
29
+ static String describe(Context context) {
30
+ String packageName = context.getPackageName();
31
+ List<String> fingerprints = signingSha1(context);
32
+ if (fingerprints.isEmpty()) {
33
+ return "package=" + packageName;
34
+ }
35
+ return "package=" + packageName + ", signing SHA-1=" + String.join(" | ", fingerprints);
36
+ }
37
+
38
+ @SuppressWarnings("deprecation")
39
+ private static List<String> signingSha1(Context context) {
40
+ List<String> out = new ArrayList<>();
41
+ try {
42
+ PackageManager pm = context.getPackageManager();
43
+ Signature[] signatures;
44
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
45
+ PackageInfo info = pm.getPackageInfo(context.getPackageName(), PackageManager.GET_SIGNING_CERTIFICATES);
46
+ signatures = info.signingInfo == null ? null
47
+ : (info.signingInfo.hasMultipleSigners()
48
+ ? info.signingInfo.getApkContentsSigners()
49
+ : info.signingInfo.getSigningCertificateHistory());
50
+ } else {
51
+ signatures = pm.getPackageInfo(context.getPackageName(), PackageManager.GET_SIGNATURES).signatures;
52
+ }
53
+ if (signatures == null) {
54
+ return out;
55
+ }
56
+ MessageDigest digest = MessageDigest.getInstance("SHA-1");
57
+ for (Signature signature : signatures) {
58
+ out.add(toColonHex(digest.digest(signature.toByteArray())));
59
+ }
60
+ } catch (Exception unreadable) {
61
+ // Diagnostics only: never let a lookup failure replace the real sign-in error.
62
+ }
63
+ return out;
64
+ }
65
+
66
+ private static String toColonHex(byte[] bytes) {
67
+ StringBuilder sb = new StringBuilder(bytes.length * 3);
68
+ for (int i = 0; i < bytes.length; i++) {
69
+ if (i > 0) {
70
+ sb.append(':');
71
+ }
72
+ sb.append(String.format("%02X", bytes[i]));
73
+ }
74
+ return sb.toString();
75
+ }
76
+ }