Skip to content

Commit 0d3c00e

Browse files
committed
adjust gotrue tests
1 parent 4d7cf9c commit 0d3c00e

File tree

4 files changed

+47
-40
lines changed

4 files changed

+47
-40
lines changed

packages/gotrue/lib/src/gotrue_client.dart

+28-19
Original file line numberDiff line numberDiff line change
@@ -924,28 +924,37 @@ class GoTrueClient {
924924

925925
/// Recover session from stringified [Session].
926926
Future<AuthResponse> recoverSession(String jsonStr) async {
927-
final session = Session.fromJson(json.decode(jsonStr));
928-
if (session == null) {
929-
await signOut();
930-
throw notifyException(AuthException('Current session is missing data.'));
931-
}
932-
933-
if (session.isExpired) {
934-
final refreshToken = session.refreshToken;
935-
if (_autoRefreshToken && refreshToken != null) {
936-
return await _callRefreshToken(refreshToken);
937-
} else {
927+
try {
928+
final session = Session.fromJson(json.decode(jsonStr));
929+
if (session == null) {
938930
await signOut();
939-
throw notifyException(AuthException('Session expired.'));
931+
throw notifyException(
932+
AuthException('Current session is missing data.'),
933+
);
940934
}
941-
} else {
942-
final shouldEmitEvent = _currentSession == null ||
943-
_currentSession?.user.id != session.user.id;
944-
_saveSession(session);
945935

946-
if (shouldEmitEvent) notifyAllSubscribers(AuthChangeEvent.tokenRefreshed);
936+
if (session.isExpired) {
937+
final refreshToken = session.refreshToken;
938+
if (_autoRefreshToken && refreshToken != null) {
939+
return await _callRefreshToken(refreshToken);
940+
} else {
941+
await signOut();
942+
throw notifyException(AuthException('Session expired.'));
943+
}
944+
} else {
945+
final shouldEmitEvent = _currentSession == null ||
946+
_currentSession?.user.id != session.user.id;
947+
_saveSession(session);
947948

948-
return AuthResponse(session: session);
949+
if (shouldEmitEvent) {
950+
notifyAllSubscribers(AuthChangeEvent.tokenRefreshed);
951+
}
952+
953+
return AuthResponse(session: session);
954+
}
955+
} catch (error) {
956+
notifyException(error);
957+
rethrow;
949958
}
950959
}
951960

@@ -1164,7 +1173,7 @@ class GoTrueClient {
11641173

11651174
/// For internal use only.
11661175
@internal
1167-
Exception notifyException(Exception exception, [StackTrace? stackTrace]) {
1176+
Object notifyException(Object exception, [StackTrace? stackTrace]) {
11681177
_onAuthStateChangeController.addError(
11691178
exception,
11701179
stackTrace ?? StackTrace.current,

packages/gotrue/test/client_test.dart

+10-17
Original file line numberDiff line numberDiff line change
@@ -373,26 +373,19 @@ void main() {
373373
final session =
374374
'{"access_token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2ODAzNDE3MDUsInN1YiI6IjRkMjU4M2RhLThkZTQtNDlkMy05Y2QxLTM3YTlhNzRmNTViZCIsImVtYWlsIjoiZmFrZTE2ODAzMzgxMDVAZW1haWwuY29tIiwicGhvbmUiOiIiLCJhcHBfbWV0YWRhdGEiOnsicHJvdmlkZXIiOiJlbWFpbCIsInByb3ZpZGVycyI6WyJlbWFpbCJdfSwidXNlcl9tZXRhZGF0YSI6eyJIZWxsbyI6IldvcmxkIn0sInJvbGUiOiIiLCJhYWwiOiJhYWwxIiwiYW1yIjpbeyJtZXRob2QiOiJwYXNzd29yZCIsInRpbWVzdGFtcCI6MTY4MDMzODEwNX1dLCJzZXNzaW9uX2lkIjoiYzhiOTg2Y2UtZWJkZC00ZGUxLWI4MjAtZjIyOWYyNjg1OGIwIn0.0x1rFlPKbIU1rZPY1SH_FNSZaXerfkFA1Y-EOlhuzUs","expires_in":3600,"refresh_token":"-yeS4omysFs9tpUYBws9Rg","token_type":"bearer","provider_token":null,"provider_refresh_token":null,"user":{"id":"4d2583da-8de4-49d3-9cd1-37a9a74f55bd","app_metadata":{"provider":"email","providers":["email"]},"user_metadata":{"Hello":"World"},"aud":"","email":"[email protected]","phone":"","created_at":"2023-04-01T08:35:05.208586Z","confirmed_at":null,"email_confirmed_at":"2023-04-01T08:35:05.220096086Z","phone_confirmed_at":null,"last_sign_in_at":"2023-04-01T08:35:05.222755878Z","role":"","updated_at":"2023-04-01T08:35:05.226938Z"},"expiresAt":1680341705}';
375375

376-
///These 3 are bundled and in sum 4 refresh token requests are made, because the first 3 fail in [RetryTestHttpClient]
377-
final future1 = Future.wait([
378-
client.recoverSession(session),
376+
///These 3 are bundled and in sum 1 refresh token requests is made, because the first 3 fail in [RetryTestHttpClient]
377+
final responses = await Future.wait([
379378
client.recoverSession(session),
380379
client.recoverSession(session),
381380
]);
382381

383-
await expectLater(future1, throwsA(isA<ClientException>()));
384-
expect(httpClient.retryCount, 1);
385-
386-
/// Again these 3 are bundled and only one refresh token request is made
387-
final future2 = Future.wait([
388-
client.recoverSession(session),
389-
client.recoverSession(session),
390-
client.recoverSession(session),
391-
]);
382+
expect(responses[0].session?.accessToken, isNotNull);
383+
expect(
384+
responses[0].session?.accessToken,
385+
responses[1].session?.accessToken,
386+
);
392387

393-
await expectLater(future2, throwsA(isA<ClientException>()));
394-
expect(client.onAuthStateChange, emits(isA<AuthState>()));
395-
expect(httpClient.retryCount, 2);
388+
expect(httpClient.retryCount, 4);
396389
});
397390

398391
test('Sign out on wrong refresh token', () async {
@@ -410,10 +403,10 @@ void main() {
410403
]),
411404
);
412405

413-
final session =
406+
final expiredSession =
414407
getSessionData(DateTime.now().subtract(Duration(hours: 1)));
415408

416-
await expectLater(client.recoverSession(session.sessionString),
409+
await expectLater(client.recoverSession(expiredSession.sessionString),
417410
throwsA(isA<AuthException>()));
418411
expect(stream, emitsError(isA<AuthException>()));
419412

packages/gotrue/test/custom_http_client.dart

+5-1
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,11 @@ class RetryTestHttpClient extends BaseClient {
7676
throw ClientException('Retry #$retryCount');
7777
}
7878
final jwt = JWT(
79-
{'exp': (DateTime.now().millisecondsSinceEpoch / 1000).round() + 60},
79+
{
80+
'exp': (DateTime.now().millisecondsSinceEpoch / 1000).round() + 60,
81+
'retry_count':
82+
retryCount, // Add retryCount so that tokens issued on different retries are different.
83+
},
8084
subject: userId1,
8185
);
8286

packages/gotrue/test/utils.dart

+4-3
Original file line numberDiff line numberDiff line change
@@ -51,13 +51,14 @@ String getServiceRoleToken(DotEnv env) {
5151
}
5252

5353
/// Construct session data for a given expiration date
54-
({String accessToken, String sessionString}) getSessionData(DateTime dateTime) {
55-
final expiresAt = dateTime.millisecondsSinceEpoch ~/ 1000;
54+
({String accessToken, String sessionString}) getSessionData(
55+
DateTime expireDateTime) {
56+
final expiresAt = expireDateTime.millisecondsSinceEpoch ~/ 1000;
5657
final accessTokenMid = base64.encode(utf8.encode(json.encode(
5758
{'exp': expiresAt, 'sub': '1234567890', 'role': 'authenticated'})));
5859
final accessToken = 'any.$accessTokenMid.any';
5960
final sessionString =
60-
'{"access_token":"$accessToken","expires_in":${dateTime.difference(DateTime.now()).inSeconds},"refresh_token":"-yeS4omysFs9tpUYBws9Rg","token_type":"bearer","provider_token":null,"provider_refresh_token":null,"user":{"id":"4d2583da-8de4-49d3-9cd1-37a9a74f55bd","app_metadata":{"provider":"email","providers":["email"]},"user_metadata":{"Hello":"World"},"aud":"","email":"[email protected]","phone":"","created_at":"2023-04-01T08:35:05.208586Z","confirmed_at":null,"email_confirmed_at":"2023-04-01T08:35:05.220096086Z","phone_confirmed_at":null,"last_sign_in_at":"2023-04-01T08:35:05.222755878Z","role":"","updated_at":"2023-04-01T08:35:05.226938Z"}}';
61+
'{"access_token":"$accessToken","expires_in":${expireDateTime.difference(DateTime.now()).inSeconds},"refresh_token":"-yeS4omysFs9tpUYBws9Rg","token_type":"bearer","provider_token":null,"provider_refresh_token":null,"user":{"id":"4d2583da-8de4-49d3-9cd1-37a9a74f55bd","app_metadata":{"provider":"email","providers":["email"]},"user_metadata":{"Hello":"World"},"aud":"","email":"[email protected]","phone":"","created_at":"2023-04-01T08:35:05.208586Z","confirmed_at":null,"email_confirmed_at":"2023-04-01T08:35:05.220096086Z","phone_confirmed_at":null,"last_sign_in_at":"2023-04-01T08:35:05.222755878Z","role":"","updated_at":"2023-04-01T08:35:05.226938Z"}}';
6162
return (accessToken: accessToken, sessionString: sessionString);
6263
}
6364

0 commit comments

Comments
 (0)