forked from nhost/nhost-dart
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth_client.dart
More file actions
953 lines (856 loc) · 28 KB
/
auth_client.dart
File metadata and controls
953 lines (856 loc) · 28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
import 'dart:async';
import 'package:http/http.dart' as http;
import 'package:meta/meta.dart';
import 'package:nhost_sdk/nhost_sdk.dart';
import 'auth_store.dart';
import 'logging.dart';
/// The Nhost authentication service.
///
/// Supports user authentication, MFA, OTP, and various user management
/// functions. implements
///
/// See https://docs.nhost.io/reference/sdk/authentication for more info.
class NhostAuthClient implements HasuraAuthClient {
/// {@macro nhost.api.NhostClient.url}
///
/// {@macro nhost.api.NhostClient.authStore}
///
/// {@macro nhost.api.NhostClient.refreshToken}
///
/// {@macro nhost.api.NhostClient.autoSignIn}
///
/// {@macro nhost.api.NhostClient.tokenRefreshInterval}
///
/// {@macro nhost.api.NhostClient.httpClientOverride}
NhostAuthClient({
required String url,
UserSession? session,
AuthStore? authStore,
Duration? tokenRefreshInterval,
http.Client? httpClient,
}) : _apiClient = ApiClient(
Uri.parse(url),
httpClient: httpClient ?? http.Client(),
),
_session = session ?? UserSession(),
_authStore = authStore ?? InMemoryAuthStore(),
_tokenRefreshInterval = tokenRefreshInterval,
_refreshTokenLock = false,
_loading = false;
/// The HTTP client used by this client's services.
final ApiClient _apiClient;
final AuthStore _authStore;
final UserSession _session;
UserSession get userSession => _session;
final List<TokenChangedCallback> _tokenChangedCallbacks = [];
final List<AuthStateChangedCallback> _authChangedCallbacks = [];
final List<SessionRefreshFailedCallback> _sessionRefreshFailedCallbacks = [];
Timer? _tokenRefreshTimer;
final Duration? _tokenRefreshInterval;
bool _refreshTokenLock;
Completer<Session>? _sessionCompleter;
/// `true` if the service is currently loading.
///
/// While loading, the authentication state is indeterminate.
bool _loading;
/// Currently logged-in user, or `null` if unauthenticated.
@override
User? get currentUser => _currentUser;
User? _currentUser;
/// Whether a user is logged in, not logged in, or if a sign-in is in process.
@override
AuthenticationState get authenticationState {
if (_loading) return AuthenticationState.inProgress;
return _session.session != null
? AuthenticationState.signedIn
: AuthenticationState.signedOut;
}
/// The currently logged-in user's Json Web Token, or `null` if
/// unauthenticated.
@override
String? get accessToken => _session.accessToken;
/// Gets the value of a JWT claim named [jwtClaim] associated with the current
/// authentication session, or `null` if not found/unauthenticated.
@override
String? getClaim(String jwtClaim) => _session.getClaim(jwtClaim);
/// Releases the service's resources.
///
/// The service's methods cannot be called past this point.
@override
void close() {
_apiClient.close();
_tokenRefreshTimer?.cancel();
}
//#region Events
/// Add a callback that will be invoked when the service's token changes.
///
/// The returned function will remove the callback when called.
@override
UnsubscribeDelegate addTokenChangedCallback(TokenChangedCallback callback) {
_tokenChangedCallbacks.add(callback);
return () {
_tokenChangedCallbacks.removeWhere((element) => element == callback);
};
}
/// Add a callback that will be invoked when the service's authentication
/// state changes.
///
/// The returned function will remove the callback when called.
@override
UnsubscribeDelegate addAuthStateChangedCallback(
AuthStateChangedCallback callback) {
_authChangedCallbacks.add(callback);
return () {
_authChangedCallbacks.removeWhere((element) => element == callback);
};
}
/// Add a callback that will be invoked when the service fails to refresh its
/// session.
///
/// Session refreshes happen periodically based on settings configured in the
/// Nhost console, and also through [signInWithRefreshToken] and
/// [signInWithStoredCredentials].
///
/// The returned function will remove the callback when called.
@override
UnsubscribeDelegate addSessionRefreshFailedCallback(
SessionRefreshFailedCallback callback) {
_sessionRefreshFailedCallbacks.add(callback);
return () {
_sessionRefreshFailedCallbacks
.removeWhere((element) => element == callback);
};
}
void _onTokenChanged() {
log.finest(
'Calling token change callbacks, '
'jwt.hashCode=${identityHashCode(accessToken)}',
);
for (final tokenChangedFunction in _tokenChangedCallbacks) {
tokenChangedFunction();
}
}
void _onAuthStateChanged(AuthenticationState authState) {
log.finest('Calling auth state change callbacks, authState=$authState');
for (final authChangedFunction in _authChangedCallbacks) {
authChangedFunction(authState);
}
}
void _onTokenRefreshFailure(Exception e, StackTrace st) {
log.finest('Calling token refresh failure callbacks');
for (final fn in _sessionRefreshFailedCallbacks) {
fn(e, st);
}
}
//#endregion
/// Creates a user from an [email] and [password].
///
/// If Nhost is configured to not automatically activate new users, the
/// returned [AuthResponse] will not contain a session. The user must first
/// activate their account by clicking an activation link sent to their email.
///
/// If [turnstileResponse] is provided, it will be included in the request headers
/// as `x-cf-turnstile-response` to support Cloudflare Turnstile protection.
///
/// Throws an [NhostException] if registration fails.
@override
Future<AuthResponse> signUp({
required String email,
required String password,
String? locale,
String? defaultRole,
Map<String, Object?>? metadata,
List<String>? roles,
String? displayName,
String? redirectTo,
String? turnstileResponse,
}) async {
log.finer('Attempting user registration');
final headers =
turnstileResponse != null ? {'x-cf-turnstile-response': turnstileResponse} : null;
final includeRoleOptions =
defaultRole != null || (roles != null && roles.isNotEmpty);
final options = {
if (metadata != null) 'metadata': metadata,
if (locale != null) 'locale': locale,
if (includeRoleOptions) 'defaultRole': defaultRole,
if (includeRoleOptions) 'allowedRoles': roles,
if (displayName != null) 'displayName': displayName,
if (redirectTo != null) 'redirectTo': redirectTo,
};
try {
final res = await _apiClient.post(
'/signup/email-password',
jsonBody: {
'email': email,
'password': password,
if (options.isNotEmpty) 'options': options,
},
responseDeserializer: AuthResponse.fromJson,
headers: headers,
);
log.finer('Registration successful');
if (res.session?.accessToken != null) {
await setSession(res.session!);
return res;
} else {
// if AUTO_ACTIVATE_NEW_USERS is false
return AuthResponse(session: null);
}
} catch (e) {
log.finer('Registration failed');
rethrow;
}
}
/// Authenticates a user using an [email] and [password].
///
/// If the user has multi-factor authentication enabled, the returned
/// [AuthResponse] will only have its [AuthResponse.mfa] field set, which can
/// then be used to complete the sign in via [completeMfaSignIn] alongside the
/// user's one-time-password.
///
/// Throws an [NhostException] if sign in fails.
@override
Future<AuthResponse> signInEmailPassword({
required String email,
required String password,
}) async {
log.finer('Attempting sign in (email-password)');
AuthResponse? res;
try {
res = await _apiClient.post(
'/signin/email-password',
jsonBody: {
'email': email,
'password': password,
},
responseDeserializer: AuthResponse.fromJson,
);
} catch (e, st) {
log.finer('Sign in failed', e, st);
await clearSession();
rethrow;
}
// If multi-factor is enabled, a second step is required before we've fully
// logged in.
if (res!.mfa != null) {
log.finer('Sign in requires MFA');
return res;
}
log.finer('Sign in successful');
await setSession(res.session!);
return res;
}
/// Authenticates a user using an ID token from a third-party provider.
///
/// This method allows users to sign in using an OpenID Connect [idToken] from a specified
/// [provider] (google, apple). An optional [nonce] parameter can be provided for additional security.
///
/// Throws an [NhostException] if sign in fails.
@override
Future<AuthResponse> signInIdToken({
required String provider,
required String idToken,
String? nonce,
String? locale,
String? defaultRole,
Map<String, Object?>? metadata,
List<String>? roles,
String? displayName,
String? redirectTo,
}) async {
log.finer('Attempting sign in (idToken)');
AuthResponse? res;
try {
res = await _apiClient.post(
'/signin/idtoken',
jsonBody: {
'provider': provider,
'idToken': idToken,
if (nonce != null) 'nonce': nonce,
if (locale != null) 'locale': locale,
if (defaultRole != null) 'defaultRole': defaultRole,
if (metadata != null) 'metadata': metadata,
if (roles != null) 'roles': roles,
if (displayName != null) 'displayName': displayName,
if (redirectTo != null) 'redirectTo': redirectTo,
},
responseDeserializer: AuthResponse.fromJson,
);
} catch (e, st) {
log.finer('Sign in failed', e, st);
await clearSession();
rethrow;
}
if (res != null) {
log.finer('Sign in successful');
await setSession(res.session!);
return res;
} else {
throw AuthServiceException(
'Sign in failed',
);
}
}
/// Links an existing user account to a third-party provider using an OpenID Connect [idToken].
///
/// This method enables linking a user account with an OpenID Connect [idToken] from a specified
/// [provider], such as "google" or "apple". You can optionally provide a [nonce] for enhanced security.
///
/// Throws an [NhostException] if the link attempt fails.
@override
Future<void> linkIdToken({
required String provider,
required String idToken,
String? nonce,
}) async {
await _apiClient.post<String>(
'/link/idtoken',
jsonBody: {
'provider': provider,
'idToken': idToken,
if (nonce != null) 'nonce': nonce,
},
headers: _session.authenticationHeaders,
);
}
/// Signs in a user with a magic link.
///
/// An email will be sent to the [email] with a link. When the user
/// clicks on the link the user will be automatically redirected to
/// [redirectTo] with a refresh token as a hash argument. This value can then
/// be used to sign in via [signInWithRefreshToken].
///
/// Throws an [NhostException] if sign in fails.
@override
Future<void> signInWithEmailPasswordless({
required String email,
String? locale,
String? defaultRole,
Map<String, Object?>? metadata,
List<String>? roles,
String? displayName,
String? redirectTo,
}) async {
log.finer('Attempting sign in (passwordless email)');
final includeRoleOptions = defaultRole != null || (roles != null && roles.isNotEmpty);
final options = {
if (metadata != null) 'metadata': metadata,
if (locale != null) 'locale': locale,
if (includeRoleOptions) 'defaultRole': defaultRole,
if (includeRoleOptions) 'allowedRoles': roles,
if (displayName != null) 'displayName': displayName,
if (redirectTo != null) 'redirectTo': redirectTo,
};
return _apiClient.post(
'/signin/passwordless/email',
jsonBody: {
'email': email,
if (options.isNotEmpty) 'options': options,
},
);
}
/// Authenticates a user anonymously.
///
/// You need to make sure anonymous signin is enabled via
/// Nhost dashboard -> settings -> Sign in methods -> Anonymous Users
/// Throws an [NhostException] if sign in fails.
@override
Future<void> signInAnonymous(
String? displayName,
String? locale,
Map<String, dynamic>? metadata,
) async {
log.finer('Attempting sign in anonymously');
AuthResponse? res;
try {
res = await _apiClient.post(
'/signin/anonymous',
jsonBody: {
if (displayName != null) 'displayName': displayName,
if (locale != null) 'locale': locale,
if (metadata != null) 'metadata': metadata
},
responseDeserializer: AuthResponse.fromJson,
);
} catch (e, st) {
log.finer('Sign in anonymously failed', e, st);
await clearSession();
rethrow;
}
if (res != null) {
log.finer('Sign in anonymously successful');
await setSession(res.session!);
}
}
/// Authenticates a user using a [phoneNumber].
///
/// The returned [AuthResponse] will only have its [AuthResponse.mfa] field
/// set, which can then be used to complete the sign in via
/// [completeSmsPasswordlessSignIn] alongside the user's one-time-password.
///
/// Throws an [NhostException] if sign in fails.
@override
Future<void> signInWithSmsPasswordless({
required String phoneNumber,
String? locale,
String? defaultRole,
Map<String, Object?>? metadata,
List<String>? roles,
String? displayName,
String? redirectTo,
}) async {
log.finer('Attempting sign in (passwordless SMS)');
final includeRoleOptions =
defaultRole != null || (roles != null && roles.isNotEmpty);
final options = {
if (metadata != null) 'metadata': metadata,
if (locale != null) 'locale': locale,
if (includeRoleOptions) 'defaultRole': defaultRole,
if (includeRoleOptions) 'allowedRoles': roles,
if (displayName != null) 'displayName': displayName,
if (redirectTo != null) 'redirectTo': redirectTo,
};
await _apiClient.post(
'/signin/passwordless/sms',
jsonBody: {
'phoneNumber': phoneNumber,
if (options.isNotEmpty) 'options': options,
},
);
}
@override
Future<AuthResponse> completeSmsPasswordlessSignIn(
String phoneNumber,
String otp,
) async {
final res = await _apiClient.post(
'/signin/passwordless/sms/otp',
jsonBody: {'phoneNumber': phoneNumber, 'otp': otp},
responseDeserializer: AuthResponse.fromJson,
);
log.finer('Sign in successful');
await setSession(res.session!);
return res;
}
/// Attempts to send an OTP to the specified [email] to begin the sign-in process
///
/// Throws an [NhostException] if the request fails
@override
Future<void> signInEmailOTP({
required String email,
String? locale,
String? defaultRole,
Map<String, Object?>? metadata,
List<String>? roles,
String? displayName,
String? redirectTo,
}) async {
log.finer('Attempting sign in (otp)');
final includeRoleOptions =
defaultRole != null || (roles != null && roles.isNotEmpty);
final options = {
if (metadata != null) 'metadata': metadata,
if (locale != null) 'locale': locale,
if (includeRoleOptions) 'defaultRole': defaultRole,
if (includeRoleOptions) 'allowedRoles': roles,
if (displayName != null) 'displayName': displayName,
if (redirectTo != null) 'redirectTo': redirectTo,
};
await _apiClient.post(
'/signin/otp/email',
jsonBody: {
'email': email,
if (options.isNotEmpty) 'options': options,
},
);
}
/// Attempts to verify the one-time password (OTP) and complete the sign-in process
///
/// Throws an [NhostException] if verification fails
@override
Future<AuthResponse> verifyEmailOTP({
required String email,
required String otp,
}) async {
final res = await _apiClient.post(
'/signin/otp/email/verify',
jsonBody: {'email': email, 'otp': otp},
responseDeserializer: AuthResponse.fromJson,
);
log.finer('Sign in successful');
await setSession(res.session!);
return res;
}
/// Attempts a sign in using the credentials stored in the [AuthStore]
/// provided during construction.
///
/// Throws an [NhostException] if sign in fails.
@override
Future<AuthResponse> signInWithStoredCredentials() async {
log.finer('Attempting sign in (stored credentials)');
final session = await _refreshSession();
return AuthResponse(session: session);
}
/// Attempts a sign in using a [refreshToken] from a previously sign in.
///
/// After logging in, the refresh token is available at
/// [Session.refreshToken].
///
/// Throws an [NhostException] if sign in fails.
@override
Future<AuthResponse> signInWithRefreshToken(String refreshToken) async {
log.finer('Attempting sign in (token)');
return AuthResponse(session: await _refreshSession(refreshToken));
}
/// Logs out the current user.
///
/// If [all] is true, all of the user's devices will be logged out.
///
/// Returns an [AuthResponse] with its fields unset.
///
/// Throws an [NhostException] if sign out fails.
@override
Future<AuthResponse> signOut({
bool all = false,
}) async {
log.finer('Attempting sign out');
final refreshToken = await _authStore.getString(
refreshTokenClientStorageKey,
);
try {
await _apiClient.post(
'/signout',
jsonBody: {
'refreshToken': refreshToken,
'all': all,
},
);
log.finer('Sign out successful');
} catch (e, st) {
log.finer('Sign out failed', e, st);
// noop
// TODO(shyndman): This probably shouldn't be a noop. If a signout fails,
// particularly in the ?all=true case, the user should know about it
}
await clearSession();
return AuthResponse(session: null);
}
/// Resends the sign-up verification email to the user with the specified
/// [email].
@override
Future<void> sendVerificationEmail({
required String email,
String? redirectTo,
}) async {
await _apiClient.post<void>(
'/user/email/send-verification-email',
jsonBody: {
'email': email,
if (redirectTo != null)
'options': {
'redirectTo': redirectTo,
},
},
headers: _session.authenticationHeaders,
);
}
//#region Email and password changes
/// Changes the email address of a logged in user.
///
/// NOTE: This function requires that your project is configured with "NEW
/// EMAIL VERIFICATION" turned OFF.
///
/// Throws an [NhostException] if changing emails fails.
@override
Future<void> changeEmail(String newEmail) async {
await _apiClient.post(
'/user/email/change',
jsonBody: {
'newEmail': newEmail,
},
headers: _session.authenticationHeaders,
);
}
/// Changes the password of the logged in user.
///
/// Throws an [NhostException] if changing passwords fails.
@override
Future<void> changePassword({
required String newPassword,
String? ticket,
}) async {
await _apiClient.post(
'/user/password',
jsonBody: {
'newPassword': newPassword,
if (ticket != null) 'ticket': ticket
},
headers: _session.authenticationHeaders,
);
}
/// Resets a user's password.
///
/// Throws an [NhostException] if requesting the password change fails.
@override
Future<void> resetPassword({
required String email,
String? redirectTo,
}) async {
await _apiClient.post(
'/user/password/reset',
jsonBody: {
'email': email,
if (redirectTo != null)
'options': {
'redirectTo': redirectTo,
},
},
);
}
//#endregion
//#region Multi-factor authentication
/// Generates an MFA (Multi-Factor Authentication) QR-code.
///
/// The user must be logged in to generate this QR-code. The user should scan
/// the QR-code with their password manager.
///
/// The password manager will return a code (one-time password) that will be
/// used to [enableMfa] and [disableMfa].
///
/// Throws an [NhostException] if MFA generation fails.
@override
Future<MultiFactorAuthResponse> generateMfa() async {
return await _apiClient.get(
'/mfa/totp/generate',
headers: _session.authenticationHeaders,
responseDeserializer: MultiFactorAuthResponse.fromJson,
);
}
/// Enable MFA (Multi-Factor Authentication).
///
/// [totp] is the one-time password generated from an OTP secret, which is
/// created via the [generateMfa] call.
///
/// Throws an [NhostException] if enabling MFA fails.
@override
Future<void> enableMfa(String totp) async {
await _apiClient.post(
'/user/mfa',
headers: _session.authenticationHeaders,
jsonBody: {
'code': totp,
'activeMfaType': 'totp',
},
);
}
/// Disable MFA (Multi-Factor Authentication).
///
/// [code] is the one-time password generated by the user's password manager.
///
/// Throws an [NhostException] if disabling MFA fails.
@override
Future<void> disableMfa(String code) async {
await _apiClient.post(
'/user/mfa',
jsonBody: {
'code': code,
'activeMfaType': '',
},
headers: _session.authenticationHeaders,
);
}
/// Complete an MFA sign in using a time-based one-time password.
///
/// This is only necessary if the user has MFA enabled.
///
/// [otp] is the OTP generated by the user's password manager, and [ticket]
/// is the [AuthResponse.mfa.ticket] returned by a preceding call to [signInEmailPassword].
///
/// Throws an [NhostException] if logging in via MFA fails.
@override
Future<AuthResponse> completeMfaSignIn({
required String otp,
required String ticket,
}) async {
final res = await _apiClient.post<AuthResponse>(
'/signin/mfa/totp',
jsonBody: {
'otp': otp,
'ticket': ticket,
},
responseDeserializer: AuthResponse.fromJson,
);
await setSession(res.session!);
return res;
}
//#endregion
//#region OAuth providers
/// Completes an OAuth provider sign in, given the Nhost OAuth provider's
/// [redirectUrl].
///
/// For more information on redirect URLs, see
/// https://docs.nhost.io/platform/authentication/social-login.
///
/// For an example of this in practice, see the `nhost_flutter_auth` package's
/// OAuthProvider example.
@override
Future<void> completeOAuthProviderSignIn(Uri redirectUrl) async {
final queryArgs = redirectUrl.queryParameters;
if (!queryArgs.containsKey(refreshTokenQueryParamName)) {
return;
}
await _refreshSession(queryArgs[refreshTokenQueryParamName]);
}
//#endregion
//#region Token and session Handling
Future<Session> _refreshSession([String? initRefreshToken]) async {
log.finest('Session refresh requested');
final storedRefreshTokenValue = await _authStore.getString(
refreshTokenClientStorageKey,
);
final refreshToken = initRefreshToken ?? storedRefreshTokenValue;
// If there's no refresh token, we're all done.
if (refreshToken == null) {
log.finest('No refresh token. Halting request.');
_loading = false;
_onAuthStateChanged(authenticationState);
throw AuthServiceException(
'No refresh token in AuthStore. Cannot authenticate.',
);
}
// Set lock to avoid two refresh token request being sent at the same time
// with the same token. If that were to happen, the last request will fail
// because the first request used the refresh token.
if (_refreshTokenLock) {
log.finest('Session refresh already in progress. Halting this request.');
// Return a future that will resolve to a session when the existing
// request completes.
_sessionCompleter ??= Completer();
return _sessionCompleter!.future;
}
try {
_refreshTokenLock = true;
// Make refresh token request
log.finest('Making session refresh request');
final res = await _apiClient.post(
'/token',
jsonBody: {
'refreshToken': refreshToken,
},
responseDeserializer: Session.fromJson,
);
await setSession(res);
_sessionCompleter?.complete(res);
return res;
} on Exception catch (e, st) {
if (e is ApiException && e.statusCode == unauthorizedStatus) {
log.finest('Unauthorized refresh token. Forcing signout.');
await signOut();
}
log.severe('Exception during token refresh', e, st);
_sessionCompleter?.completeError(e, st);
// Inform subscribers of the failure. If there are none, rethrow the
// exception.
_onTokenRefreshFailure(e, st);
rethrow;
} finally {
// Release lock
_refreshTokenLock = false;
_sessionCompleter = null;
}
}
/// Updates the [NhostAuthClient] to begin identifying as the user described by
/// [session].
@override
@visibleForTesting
Future<void> setSession(Session session) async {
// It is CRITICAL that this function be awaited before returning to the
// user. Failure to do so will result in very difficult to track down race
// conditions.
log.finest(
'Setting session, accessToken.hashCode='
'${identityHashCode(session.accessToken)}',
);
final previouslyAuthenticated = authenticationState;
_session.session = session;
_currentUser = session.user;
if (session.refreshToken != null) {
await _authStore.setString(
refreshTokenClientStorageKey,
session.refreshToken!,
);
}
final accessTokenExpiresIn = session.accessTokenExpiresIn;
final refreshTimerDuration = _tokenRefreshInterval ??
(accessTokenExpiresIn != null
? accessTokenExpiresIn - Duration(seconds: 45)
: Duration(seconds: 855)); // 45 sec before expiry
// Ensure that the previous timer is cancelled.
_tokenRefreshTimer?.cancel();
// Start refresh token interval after logging in.
log.finest('Creating token refresh timer, duration=$refreshTimerDuration');
_tokenRefreshTimer = Timer(
refreshTimerDuration,
() {
log.finest('Refresh timer elapsed');
_refreshSession();
},
);
// We're ready!
_loading = false;
_onTokenChanged();
if (previouslyAuthenticated != AuthenticationState.signedIn) {
_onAuthStateChanged(AuthenticationState.signedIn);
}
}
/// Clears the active session, if any, and removes all derived state.
///
/// It is CRITICAL that this function be awaited before returning to the user.
/// Failure to do so will result in very difficult to track down race
/// conditions.
@override
@visibleForTesting
Future<void> clearSession() async {
log.finest('Clearing session');
if (_tokenRefreshTimer != null) {
_tokenRefreshTimer!.cancel();
_tokenRefreshTimer = null;
}
// Early exit
//
// There could be case when the authenticationState is inProgress and
// signout is called. For example, if the refresh token has expired. In that
// case it is important to to clear out the session and remove the refresh
// token from storage.
if (authenticationState == AuthenticationState.signedOut) {
return;
}
_session.clear();
await _authStore.removeItem(refreshTokenClientStorageKey);
_currentUser = null;
_loading = false;
_onTokenChanged();
_onAuthStateChanged(AuthenticationState.signedOut);
}
@override
String toString() {
return {
'accessToken': accessToken,
'refreshToken': _session.session?.refreshToken,
'accessTokenExpiresIn': _session.session?.accessTokenExpiresIn,
'userEmail': _session.session?.user?.email,
}.toString();
}
//#endregion
}
class AuthServiceException implements NhostException {
AuthServiceException([this.message]);
final dynamic message;
@override
String toString() {
Object? message = this.message;
if (message == null) return "AuthServiceException";
return "AuthServiceException: $message";
}
}