Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions packages/google_sign_in/google_sign_in_web/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
## 1.1.1

* Throws a more actionable error when init is called more than once
Comment on lines +1 to +3
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This needs to be combined with the items from NEXT section:

## 1.1.1

* Throws a more actionable error when init is called more than once
* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8.

* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8.

## NEXT

* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,8 +65,36 @@ void main() {
await plugin.init(
const InitParameters(clientId: 'some-non-null-client-id'),
);
});

testWidgets('throws if init is called twice', (_) async {
await plugin.init(
const InitParameters(clientId: 'some-non-null-client-id'),
);

// Calling init() a second time should throw state error
expect(
() => plugin.init(
const InitParameters(clientId: 'some-non-null-client-id'),
),
throwsStateError,
);
});

testWidgets('throws if init is called twice synchronously', (_) async {
final Future<void> firstInit = plugin.init(
const InitParameters(clientId: 'some-non-null-client-id'),
);

// Calling init() a second time synchronously should throw state error
expect(
() => plugin.init(
const InitParameters(clientId: 'some-non-null-client-id'),
),
throwsStateError,
);

expect(plugin.initialized, completes);
await firstInit;
});

testWidgets('asserts clientId is not null', (_) async {
Expand All @@ -85,35 +113,6 @@ void main() {
);
}, throwsAssertionError);
});

testWidgets('must be called for most of the API to work', (_) async {
expect(() async {
await plugin.attemptLightweightAuthentication(
const AttemptLightweightAuthenticationParameters(),
);
}, throwsStateError);

expect(() async {
await plugin.clientAuthorizationTokensForScopes(
const ClientAuthorizationTokensForScopesParameters(
request: AuthorizationRequestDetails(
scopes: <String>[],
userId: null,
email: null,
promptIfUnauthorized: false,
),
),
);
}, throwsStateError);

expect(() async {
await plugin.signOut(const SignOutParams());
}, throwsStateError);

expect(() async {
await plugin.disconnect(const DisconnectParams());
}, throwsStateError);
});
});

group('support queries', () {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,10 +49,14 @@ class GoogleSignInPlugin extends GoogleSignInPlatform {
@visibleForTesting GisSdkClient? debugOverrideGisSdkClient,
@visibleForTesting
StreamController<AuthenticationEvent>? debugAuthenticationController,
}) : _gisSdkClient = debugOverrideGisSdkClient,
_authenticationController =
}) : _authenticationController =
debugAuthenticationController ??
StreamController<AuthenticationEvent>.broadcast() {
// Only set _gisSdkClient if debugOverrideGisSdkClient is provided
if (debugOverrideGisSdkClient != null) {
_gisSdkClient = debugOverrideGisSdkClient;
}

autoDetectedClientId = web.document
.querySelector(clientIdMetaSelector)
?.getAttribute(clientIdAttributeName);
Expand All @@ -68,51 +72,28 @@ class GoogleSignInPlugin extends GoogleSignInPlatform {

// A future that completes when the JS loader is done.
late Future<void> _jsSdkLoadedFuture;
// A future that completes when the `init` call is done.
Completer<void>? _initCalled;

/// A completer used to track whether [init] has finished.
final Completer<void> _initCalled = Completer<void>();

/// A boolean flag to track if [init] has been called.
///
/// This is used to prevent race conditions when [init] is called multiple
/// times without awaiting.
bool _isInitCalled = false;

// A StreamController to communicate status changes from the GisSdkClient.
final StreamController<AuthenticationEvent> _authenticationController;

// The instance of [GisSdkClient] backing the plugin.
GisSdkClient? _gisSdkClient;

// A convenience getter to avoid using ! when accessing _gisSdkClient, and
// providing a slightly better error message when it is Null.
GisSdkClient get _gisClient {
assert(
_gisSdkClient != null,
'GIS Client not initialized. '
'GoogleSignInPlugin::init() or GoogleSignInPlugin::initWithParams() '
'must be called before any other method in this plugin.',
);
return _gisSdkClient!;
}

// This method throws if init or initWithParams hasn't been called at some
// point in the past. It is used by the [initialized] getter to ensure that
// users can't await on a Future that will never resolve.
void _assertIsInitCalled() {
if (_initCalled == null) {
throw StateError(
'GoogleSignInPlugin::init() or GoogleSignInPlugin::initWithParams() '
'must be called before any other method in this plugin.',
);
}
}
// Using late final ensures it can only be set once and throws if accessed before initialization.
late final GisSdkClient _gisSdkClient;

/// A future that resolves when the plugin is fully initialized.
///
/// This ensures that the SDK has been loaded, and that the `init` method
/// has finished running.
@visibleForTesting
Future<void> get initialized {
_assertIsInitCalled();
return Future.wait<void>(<Future<void>>[
_jsSdkLoadedFuture,
_initCalled!.future,
]);
}
Future<void> get _initialized => _initCalled.future;

/// Stores the client ID if it was set in a meta-tag of the page.
@visibleForTesting
Expand All @@ -125,6 +106,14 @@ class GoogleSignInPlugin extends GoogleSignInPlatform {

@override
Future<void> init(InitParameters params) async {
// Throw if init() is called more than once
if (_isInitCalled) {
throw StateError(
'init() has already been called. Calling init() more than once results in undefined behavior.',
);
}
_isInitCalled = true;

final String? appClientId = params.clientId ?? autoDetectedClientId;
assert(
appClientId != null,
Expand All @@ -138,27 +127,25 @@ class GoogleSignInPlugin extends GoogleSignInPlatform {
'serverClientId is not supported on Web.',
);

_initCalled = Completer<void>();

await _jsSdkLoadedFuture;

_gisSdkClient ??= GisSdkClient(
_gisSdkClient = GisSdkClient(
clientId: appClientId!,
nonce: params.nonce,
hostedDomain: params.hostedDomain,
authenticationController: _authenticationController,
loggingEnabled: kDebugMode,
);

_initCalled!.complete(); // Signal that `init` is fully done.
_initCalled.complete();
}

@override
Future<AuthenticationResults?>? attemptLightweightAuthentication(
AttemptLightweightAuthenticationParameters params,
) {
initialized.then((void value) {
_gisClient.requestOneTap();
_initialized.then((void value) {
_gisSdkClient.requestOneTap();
});
// One tap does not necessarily return immediately, and may never return,
// so clients should not await it. Return null to signal that.
Expand All @@ -183,26 +170,26 @@ class GoogleSignInPlugin extends GoogleSignInPlatform {

@override
Future<void> signOut(SignOutParams params) async {
await initialized;
await _initialized;

await _gisClient.signOut();
await _gisSdkClient.signOut();
}

@override
Future<void> disconnect(DisconnectParams params) async {
await initialized;
await _initialized;

await _gisClient.disconnect();
await _gisSdkClient.disconnect();
}

@override
Future<ClientAuthorizationTokenData?> clientAuthorizationTokensForScopes(
ClientAuthorizationTokensForScopesParameters params,
) async {
await initialized;
await _initialized;
_validateScopes(params.request.scopes);

final String? token = await _gisClient.requestScopes(
final String? token = await _gisSdkClient.requestScopes(
params.request.scopes,
promptIfUnauthorized: params.request.promptIfUnauthorized,
userHint: params.request.userId,
Expand All @@ -216,7 +203,7 @@ class GoogleSignInPlugin extends GoogleSignInPlatform {
Future<ServerAuthorizationTokenData?> serverAuthorizationTokensForScopes(
ServerAuthorizationTokensForScopesParameters params,
) async {
await initialized;
await _initialized;
_validateScopes(params.request.scopes);

// There is no way to know whether the flow will prompt in advance, so
Expand All @@ -225,7 +212,9 @@ class GoogleSignInPlugin extends GoogleSignInPlatform {
return null;
}

final String? code = await _gisClient.requestServerAuthCode(params.request);
final String? code = await _gisSdkClient.requestServerAuthCode(
params.request,
);
return code == null
? null
: ServerAuthorizationTokenData(serverAuthCode: code);
Expand All @@ -247,8 +236,8 @@ class GoogleSignInPlugin extends GoogleSignInPlatform {
Future<void> clearAuthorizationToken(
ClearAuthorizationTokenParams params,
) async {
await initialized;
return _gisClient.clearAuthorizationToken(params.accessToken);
await _initialized;
return _gisSdkClient.clearAuthorizationToken(params.accessToken);
}

@override
Expand Down Expand Up @@ -278,13 +267,13 @@ class GoogleSignInPlugin extends GoogleSignInPlatform {
configuration ?? GSIButtonConfiguration();
return FutureBuilder<void>(
key: Key(config.hashCode.toString()),
future: initialized,
future: _initialized,
builder: (BuildContext context, AsyncSnapshot<void> snapshot) {
if (snapshot.hasData) {
return FlexHtmlElementView(
viewType: 'gsi_login_button',
onElementCreated: (Object element) {
_gisClient.renderButton(element, config);
_gisSdkClient.renderButton(element, config);
},
);
}
Expand Down
2 changes: 1 addition & 1 deletion packages/google_sign_in/google_sign_in_web/pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ description: Flutter plugin for Google Sign-In, a secure authentication system
for signing in with a Google account on Android, iOS and Web.
repository: https://github.com/flutter/packages/tree/main/packages/google_sign_in/google_sign_in_web
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+google_sign_in%22
version: 1.1.0
version: 1.1.1

environment:
sdk: ^3.8.0
Expand Down