-
-
Notifications
You must be signed in to change notification settings - Fork 192
/
gotrue_client.dart
1308 lines (1166 loc) · 42.2 KB
/
gotrue_client.dart
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
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import 'dart:async';
import 'dart:convert';
import 'dart:math';
import 'package:collection/collection.dart';
import 'package:gotrue/gotrue.dart';
import 'package:gotrue/src/constants.dart';
import 'package:gotrue/src/fetch.dart';
import 'package:gotrue/src/helper.dart';
import 'package:gotrue/src/types/auth_response.dart';
import 'package:gotrue/src/types/fetch_options.dart';
import 'package:http/http.dart';
import 'package:jwt_decode/jwt_decode.dart';
import 'package:meta/meta.dart';
import 'package:retry/retry.dart';
import 'package:rxdart/subjects.dart';
import 'package:logging/logging.dart';
import 'broadcast_stub.dart' if (dart.library.html) './broadcast_web.dart'
as web;
import 'version.dart';
part 'gotrue_mfa_api.dart';
/// {@template gotrue_client}
/// API client to interact with gotrue server.
///
/// [url] URL of gotrue instance
///
/// [autoRefreshToken] whether to refresh the token automatically or not. Defaults to true.
///
/// [httpClient] custom http client.
///
/// [asyncStorage] local storage to store pkce code verifiers. Required when using the pkce flow.
///
/// Set [flowType] to [AuthFlowType.implicit] to perform old implicit auth flow.
/// {@endtemplate}
class GoTrueClient {
/// Namespace for the GoTrue API methods.
/// These can be used for example to get a user from a JWT in a server environment or reset a user's password.
late final GoTrueAdminApi admin;
/// Namespace for the GoTrue MFA API methods.
late final GoTrueMFAApi mfa;
/// The currently logged in user or null.
User? _currentUser;
/// The session object for the currently logged in user or null.
Session? _currentSession;
final String _url;
final Map<String, String> _headers;
final Client? _httpClient;
late final GotrueFetch _fetch = GotrueFetch(_httpClient);
late bool _autoRefreshToken;
Timer? _autoRefreshTicker;
/// Completer to combine multiple simultaneous token refresh requests.
Completer<AuthResponse>? _refreshTokenCompleter;
final _onAuthStateChangeController = BehaviorSubject<AuthState>();
final _onAuthStateChangeControllerSync =
BehaviorSubject<AuthState>(sync: true);
/// Local storage to store pkce code verifiers.
final GotrueAsyncStorage? _asyncStorage;
/// Receive a notification every time an auth event happens.
///
/// ```dart
/// supabase.auth.onAuthStateChange.listen((data) {
/// final AuthChangeEvent event = data.event;
/// final Session? session = data.session;
/// if(event == AuthChangeEvent.signedIn) {
/// // handle signIn event
/// }
/// });
/// ```
Stream<AuthState> get onAuthStateChange =>
_onAuthStateChangeController.stream;
/// Don't use this, it's for internal use only.
@internal
Stream<AuthState> get onAuthStateChangeSync =>
_onAuthStateChangeControllerSync.stream;
final AuthFlowType _flowType;
final _log = Logger('supabase.auth');
/// Proxy to the web BroadcastChannel API. Should be null on non-web platforms.
BroadcastChannel? _broadcastChannel;
StreamSubscription? _broadcastChannelSubscription;
/// {@macro gotrue_client}
GoTrueClient({
String? url,
Map<String, String>? headers,
bool? autoRefreshToken,
Client? httpClient,
GotrueAsyncStorage? asyncStorage,
AuthFlowType flowType = AuthFlowType.pkce,
}) : _url = url ?? Constants.defaultGotrueUrl,
_headers = {
...Constants.defaultHeaders,
...?headers,
},
_httpClient = httpClient,
_asyncStorage = asyncStorage,
_flowType = flowType {
_autoRefreshToken = autoRefreshToken ?? true;
final gotrueUrl = url ?? Constants.defaultGotrueUrl;
_log.config(
'Initialize GoTrueClient v$version with url: $_url, autoRefreshToken: $_autoRefreshToken, flowType: $_flowType, tickDuration: ${Constants.autoRefreshTickDuration}, tickThreshold: ${Constants.autoRefreshTickThreshold}');
_log.finest('Initialize with headers: $_headers');
admin = GoTrueAdminApi(
gotrueUrl,
headers: _headers,
httpClient: httpClient,
);
mfa = GoTrueMFAApi(
client: this,
fetch: _fetch,
);
if (_autoRefreshToken) {
startAutoRefresh();
}
_mayStartBroadcastChannel();
}
/// Getter for the headers
Map<String, String> get headers => _headers;
/// Returns the current logged in user, if any;
///
/// Use [currentSession] to determine whether the user has an active session,
/// because [currentUser] can be non-null without an active session, such as
/// when the user signed up using email and password but has not confirmed
/// their email address.
User? get currentUser => _currentUser;
/// Returns the current session, if any;
Session? get currentSession => _currentSession;
/// Creates a new anonymous user.
///
/// Returns An `AuthResponse` with a session where the `is_anonymous` claim
/// in the access token JWT is set to true
Future<AuthResponse> signInAnonymously({
Map<String, dynamic>? data,
String? captchaToken,
}) async {
final response = await _fetch.request(
'$_url/signup',
RequestMethodType.post,
options: GotrueRequestOptions(
headers: _headers,
body: {
'data': data ?? {},
'gotrue_meta_security': {'captcha_token': captchaToken},
},
),
);
final authResponse = AuthResponse.fromJson(response);
final session = authResponse.session;
if (session != null) {
_saveSession(session);
notifyAllSubscribers(AuthChangeEvent.signedIn);
}
return authResponse;
}
/// Creates a new user.
///
/// Be aware that if a user account exists in the system you may get back an
/// error message that attempts to hide this information from the user.
/// This method has support for PKCE via email signups. The PKCE flow cannot be used when autoconfirm is enabled.
///
/// Returns a logged-in session if the server has "autoconfirm" ON, but only a user if the server has "autoconfirm" OFF
///
/// [email] is the user's email address
///
/// [phone] is the user's phone number WITH international prefix
///
/// [password] is the password of the user
///
/// [data] sets [User.userMetadata] without an extra call to [updateUser]
///
/// [channel] Messaging channel to use (e.g. whatsapp or sms)
Future<AuthResponse> signUp({
String? email,
String? phone,
required String password,
String? emailRedirectTo,
Map<String, dynamic>? data,
String? captchaToken,
OtpChannel channel = OtpChannel.sms,
}) async {
assert((email != null && phone == null) || (email == null && phone != null),
'You must provide either an email or phone number');
late final Map<String, dynamic> response;
if (email != null) {
String? codeChallenge;
if (_flowType == AuthFlowType.pkce) {
assert(_asyncStorage != null,
'You need to provide asyncStorage to perform pkce flow.');
final codeVerifier = generatePKCEVerifier();
await _asyncStorage!.setItem(
key: '${Constants.defaultStorageKey}-code-verifier',
value: codeVerifier);
codeChallenge = generatePKCEChallenge(codeVerifier);
}
response = await _fetch.request(
'$_url/signup',
RequestMethodType.post,
options: GotrueRequestOptions(
headers: _headers,
redirectTo: emailRedirectTo,
body: {
'email': email,
'password': password,
'data': data,
'gotrue_meta_security': {'captcha_token': captchaToken},
'code_challenge': codeChallenge,
'code_challenge_method': codeChallenge != null ? 's256' : null,
},
),
);
} else if (phone != null) {
final body = {
'phone': phone,
'password': password,
'data': data,
'gotrue_meta_security': {'captcha_token': captchaToken},
'channel': channel.name,
};
final fetchOptions = GotrueRequestOptions(headers: _headers, body: body);
response = await _fetch.request('$_url/signup', RequestMethodType.post,
options: fetchOptions) as Map<String, dynamic>;
} else {
throw AuthException(
'You must provide either an email or phone number and a password');
}
final authResponse = AuthResponse.fromJson(response);
final session = authResponse.session;
if (session != null) {
_saveSession(session);
notifyAllSubscribers(AuthChangeEvent.signedIn);
}
return authResponse;
}
/// Log in an existing user with an email and password or phone and password.
Future<AuthResponse> signInWithPassword({
String? email,
String? phone,
required String password,
String? captchaToken,
}) async {
late final Map<String, dynamic> response;
if (email != null) {
response = await _fetch.request(
'$_url/token',
RequestMethodType.post,
options: GotrueRequestOptions(
headers: _headers,
body: {
'email': email,
'password': password,
'gotrue_meta_security': {'captcha_token': captchaToken},
},
query: {'grant_type': 'password'},
),
);
} else if (phone != null) {
response = await _fetch.request(
'$_url/token',
RequestMethodType.post,
options: GotrueRequestOptions(
headers: _headers,
body: {
'phone': phone,
'password': password,
'gotrue_meta_security': {'captcha_token': captchaToken},
},
query: {'grant_type': 'password'},
),
);
} else {
throw AuthException(
'You must provide either an email, phone number, a third-party provider or OpenID Connect.',
);
}
final authResponse = AuthResponse.fromJson(response);
if (authResponse.session?.accessToken != null) {
_saveSession(authResponse.session!);
notifyAllSubscribers(AuthChangeEvent.signedIn);
}
return authResponse;
}
/// Generates a link to log in an user via a third-party provider.
Future<OAuthResponse> getOAuthSignInUrl({
required OAuthProvider provider,
String? redirectTo,
String? scopes,
Map<String, String>? queryParams,
}) async {
return _getUrlForProvider(
provider,
url: '$_url/authorize',
redirectTo: redirectTo,
scopes: scopes,
queryParams: queryParams,
);
}
/// Verifies the PKCE code verifyer and retrieves a session.
Future<AuthSessionUrlResponse> exchangeCodeForSession(String authCode) async {
assert(_asyncStorage != null,
'You need to provide asyncStorage to perform pkce flow.');
final codeVerifierRawString = await _asyncStorage!
.getItem(key: '${Constants.defaultStorageKey}-code-verifier');
if (codeVerifierRawString == null) {
throw AuthException('Code verifier could not be found in local storage.');
}
final codeVerifier = codeVerifierRawString.split('/').first;
final eventName = codeVerifierRawString.split('/').last;
final redirectType = AuthChangeEventExtended.fromString(eventName);
final Map<String, dynamic> response = await _fetch.request(
'$_url/token',
RequestMethodType.post,
options: GotrueRequestOptions(
headers: _headers,
body: {
'auth_code': authCode,
'code_verifier': codeVerifier,
},
query: {
'grant_type': 'pkce',
},
),
);
await _asyncStorage!
.removeItem(key: '${Constants.defaultStorageKey}-code-verifier');
final authSessionUrlResponse = AuthSessionUrlResponse(
session: Session.fromJson(response)!, redirectType: redirectType?.name);
final session = authSessionUrlResponse.session;
_saveSession(session);
if (redirectType == AuthChangeEvent.passwordRecovery) {
notifyAllSubscribers(AuthChangeEvent.passwordRecovery);
} else {
notifyAllSubscribers(AuthChangeEvent.signedIn);
}
return authSessionUrlResponse;
}
/// Allows signing in with an ID token issued by certain supported providers.
/// The [idToken] is verified for validity and a new session is established.
/// This method of signing in only supports [OAuthProvider.google], [OAuthProvider.apple], [OAuthProvider.kakao] or [OAuthProvider.keycloak].
///
/// If the ID token contains an `at_hash` claim, then [accessToken] must be
/// provided to compare its hash with the value in the ID token.
///
/// If the ID token contains a `nonce` claim, then [nonce] must be
/// provided to compare its hash with the value in the ID token.
///
/// [captchaToken] is the verification token received when the user
/// completes the captcha on the app.
///
/// This method is experimental.
@experimental
Future<AuthResponse> signInWithIdToken({
required OAuthProvider provider,
required String idToken,
String? accessToken,
String? nonce,
String? captchaToken,
}) async {
if (provider != OAuthProvider.google &&
provider != OAuthProvider.apple &&
provider != OAuthProvider.kakao &&
provider != OAuthProvider.keycloak) {
throw AuthException('Provider must be '
'${OAuthProvider.google.name}, ${OAuthProvider.apple.name}, ${OAuthProvider.kakao.name} or ${OAuthProvider.keycloak.name}.');
}
final response = await _fetch.request(
'$_url/token',
RequestMethodType.post,
options: GotrueRequestOptions(
headers: _headers,
body: {
'provider': provider.snakeCase,
'id_token': idToken,
'nonce': nonce,
'gotrue_meta_security': {'captcha_token': captchaToken},
'access_token': accessToken,
},
query: {'grant_type': 'id_token'},
),
);
final authResponse = AuthResponse.fromJson(response);
if (authResponse.session == null) {
throw AuthException(
'An error occurred on token verification.',
);
}
_saveSession(authResponse.session!);
notifyAllSubscribers(AuthChangeEvent.signedIn);
return authResponse;
}
/// Log in a user using magiclink or a one-time password (OTP).
///
/// If the `{{ .ConfirmationURL }}` variable is specified in the email template, a magiclink will be sent.
///
/// If the `{{ .Token }}` variable is specified in the email template, an OTP will be sent.
///
/// If you're using phone sign-ins, only an OTP will be sent. You won't be able to send a magiclink for phone sign-ins.
///
/// If [shouldCreateUser] is set to false, this method will not create a new user. Defaults to true.
///
/// [emailRedirectTo] can be used to specify the redirect URL embedded in the email link
///
/// [data] can be used to set the user's metadata, which maps to the `auth.users.user_metadata` column.
///
/// [captchaToken] Verification token received when the user completes the captcha on the site.
///
/// [channel] Messaging channel to use (e.g. whatsapp or sms)
Future<void> signInWithOtp({
String? email,
String? phone,
String? emailRedirectTo,
bool? shouldCreateUser,
Map<String, dynamic>? data,
String? captchaToken,
OtpChannel channel = OtpChannel.sms,
}) async {
if (email != null) {
String? codeChallenge;
if (_flowType == AuthFlowType.pkce) {
assert(_asyncStorage != null,
'You need to provide asyncStorage to perform pkce flow.');
final codeVerifier = generatePKCEVerifier();
await _asyncStorage!.setItem(
key: '${Constants.defaultStorageKey}-code-verifier',
value: codeVerifier);
codeChallenge = generatePKCEChallenge(codeVerifier);
}
await _fetch.request(
'$_url/otp',
RequestMethodType.post,
options: GotrueRequestOptions(
headers: _headers,
redirectTo: emailRedirectTo,
body: {
'email': email,
'data': data ?? {},
'create_user': shouldCreateUser ?? true,
'gotrue_meta_security': {'captcha_token': captchaToken},
'code_challenge': codeChallenge,
'code_challenge_method': codeChallenge != null ? 's256' : null,
},
),
);
return;
}
if (phone != null) {
final body = {
'phone': phone,
'data': data ?? {},
'create_user': shouldCreateUser ?? true,
'gotrue_meta_security': {'captcha_token': captchaToken},
'channel': channel.name,
};
final fetchOptions = GotrueRequestOptions(headers: _headers, body: body);
await _fetch.request(
'$_url/otp',
RequestMethodType.post,
options: fetchOptions,
);
return;
}
throw AuthException(
'You must provide either an email, phone number, a third-party provider or OpenID Connect.',
);
}
/// Log in a user given a User supplied OTP received via mobile.
///
/// [phone] is the user's phone number WITH international prefix
///
/// [token] is the token that user was sent to their mobile phone
///
/// [tokenHash] is the token used in an email link
Future<AuthResponse> verifyOTP({
String? email,
String? phone,
String? token,
required OtpType type,
String? redirectTo,
String? captchaToken,
String? tokenHash,
}) async {
assert((email != null && phone == null) || (email == null && phone != null),
'`email` or `phone` needs to be specified.');
assert(token != null || tokenHash != null,
'`token` or `tokenHash` needs to be specified.');
final body = {
if (email != null) 'email': email,
if (phone != null) 'phone': phone,
if (token != null) 'token': token,
'type': type.snakeCase,
'redirect_to': redirectTo,
'gotrue_meta_security': {'captchaToken': captchaToken},
if (tokenHash != null) 'token_hash': tokenHash,
};
final fetchOptions = GotrueRequestOptions(headers: _headers, body: body);
final response = await _fetch
.request('$_url/verify', RequestMethodType.post, options: fetchOptions);
final authResponse = AuthResponse.fromJson(response);
if (authResponse.session == null) {
throw AuthException(
'An error occurred on token verification.',
);
}
_saveSession(authResponse.session!);
notifyAllSubscribers(type == OtpType.recovery
? AuthChangeEvent.passwordRecovery
: AuthChangeEvent.signedIn);
return authResponse;
}
/// Obtains a URL to perform a single-sign on using an enterprise Identity
/// Provider. The redirect URL is implementation and SSO protocol specific.
///
/// You can use it by providing a SSO domain. Typically you can extract this
/// domain by asking users for their email address. If this domain is
/// registered on the Auth instance the redirect will use that organization's
/// currently active SSO Identity Provider for the login.
///
/// If you have built an organization-specific login page, you can use the
/// organization's SSO Identity Provider UUID directly instead.
Future<String> getSSOSignInUrl({
String? providerId,
String? domain,
String? redirectTo,
String? captchaToken,
}) async {
assert(
providerId != null || domain != null,
'providerId or domain has to be provided.',
);
String? codeChallenge;
String? codeChallengeMethod;
if (_flowType == AuthFlowType.pkce) {
assert(_asyncStorage != null,
'You need to provide asyncStorage to perform pkce flow.');
final codeVerifier = generatePKCEVerifier();
await _asyncStorage!.setItem(
key: '${Constants.defaultStorageKey}-code-verifier',
value: codeVerifier);
codeChallenge = generatePKCEChallenge(codeVerifier);
codeChallengeMethod = codeVerifier == codeChallenge ? 'plain' : 's256';
}
final res = await _fetch.request('$_url/sso', RequestMethodType.post,
options: GotrueRequestOptions(
body: {
if (providerId != null) 'provider_id': providerId,
if (domain != null) 'domain': domain,
if (redirectTo != null) 'redirect_to': redirectTo,
if (captchaToken != null)
'gotrue_meta_security': {'captcha_token': captchaToken},
'skip_http_redirect': true,
'code_challenge': codeChallenge,
'code_challenge_method': codeChallengeMethod,
},
headers: _headers,
));
return res['url'] as String;
}
/// Returns a new session, regardless of expiry status.
/// Takes in an optional current session. If not passed in, then refreshSession() will attempt to retrieve it from getSession().
/// If the current session's refresh token is invalid, an error will be thrown.
Future<AuthResponse> refreshSession([String? refreshToken]) async {
if (currentSession?.accessToken == null) {
_log.warning("Can't refresh session, no current session found.");
throw AuthSessionMissingException();
}
_log.info('Refresh session');
final currentSessionRefreshToken =
refreshToken ?? _currentSession?.refreshToken;
if (currentSessionRefreshToken == null) {
throw AuthSessionMissingException();
}
return await _callRefreshToken(currentSessionRefreshToken);
}
/// Sends a reauthentication OTP to the user's email or phone number.
///
/// Requires the user to be signed-in.
Future<void> reauthenticate() async {
final session = currentSession;
if (session == null) {
throw AuthSessionMissingException();
}
final options =
GotrueRequestOptions(headers: headers, jwt: session.accessToken);
await _fetch.request(
'$_url/reauthenticate',
RequestMethodType.get,
options: options,
);
}
/// Resends an existing signup confirmation email, email change email, SMS OTP or phone change OTP.
///
/// For [type] of [OtpType.signup] or [OtpType.emailChange] [email] must be
/// provided, and for [type] or [OtpType.sms] or [OtpType.phoneChange],
/// [phone] must be provided
Future<ResendResponse> resend({
String? email,
String? phone,
required OtpType type,
String? emailRedirectTo,
String? captchaToken,
}) async {
assert((email != null && phone == null) || (email == null && phone != null),
'`email` or `phone` needs to be specified.');
if (email != null) {
assert([OtpType.signup, OtpType.emailChange].contains(type),
'email must be provided for type ${type.name}');
}
if (phone != null) {
assert([OtpType.sms, OtpType.phoneChange].contains(type),
'phone must be provided for type ${type.name}');
}
final body = {
if (email != null) 'email': email,
if (phone != null) 'phone': phone,
'type': type.snakeCase,
'gotrue_meta_security': {'captcha_token': captchaToken},
};
final options = GotrueRequestOptions(
headers: _headers,
body: body,
redirectTo: emailRedirectTo,
);
final response = await _fetch.request(
'$_url/resend',
RequestMethodType.post,
options: options,
);
if ((response as Map).containsKey(['message_id'])) {
return ResendResponse(messageId: response['message_id']);
} else {
return ResendResponse();
}
}
/// Gets the current user details from current session or custom [jwt]
Future<UserResponse> getUser([String? jwt]) async {
if (jwt == null && currentSession?.accessToken == null) {
throw AuthSessionMissingException();
}
final options = GotrueRequestOptions(
headers: _headers,
jwt: jwt ?? currentSession?.accessToken,
);
final response = await _fetch.request(
'$_url/user',
RequestMethodType.get,
options: options,
);
return UserResponse.fromJson(response);
}
/// Updates user data, if there is a logged in user.
Future<UserResponse> updateUser(
UserAttributes attributes, {
String? emailRedirectTo,
}) async {
final accessToken = currentSession?.accessToken;
if (accessToken == null) {
throw AuthSessionMissingException();
}
final body = attributes.toJson();
final options = GotrueRequestOptions(
headers: _headers,
body: body,
jwt: accessToken,
redirectTo: emailRedirectTo,
);
final response = await _fetch.request('$_url/user', RequestMethodType.put,
options: options);
final userResponse = UserResponse.fromJson(response);
_currentUser = userResponse.user;
_currentSession = currentSession?.copyWith(user: userResponse.user);
notifyAllSubscribers(AuthChangeEvent.userUpdated);
return userResponse;
}
/// Sets the session data from refresh_token and returns the current session.
Future<AuthResponse> setSession(String refreshToken) async {
if (refreshToken.isEmpty) {
throw AuthSessionMissingException('Refresh token cannot be empty');
}
return await _callRefreshToken(refreshToken);
}
/// Gets the session data from a magic link or oauth2 callback URL
Future<AuthSessionUrlResponse> getSessionFromUrl(
Uri originUrl, {
bool storeSession = true,
}) async {
var url = originUrl;
if (originUrl.hasQuery) {
final decoded = originUrl.toString().replaceAll('#', '&');
url = Uri.parse(decoded);
} else {
final decoded = originUrl.toString().replaceAll('#', '?');
url = Uri.parse(decoded);
}
final errorDescription = url.queryParameters['error_description'];
final errorCode = url.queryParameters['error_code'];
final error = url.queryParameters['error'];
if (errorDescription != null) {
throw AuthException(
errorDescription,
statusCode: errorCode,
code: error,
);
}
if (_flowType == AuthFlowType.pkce) {
final authCode = originUrl.queryParameters['code'];
if (authCode == null) {
throw AuthPKCEGrantCodeExchangeError(
'No code detected in query parameters.');
}
return await exchangeCodeForSession(authCode);
}
final accessToken = url.queryParameters['access_token'];
final expiresIn = url.queryParameters['expires_in'];
final refreshToken = url.queryParameters['refresh_token'];
final tokenType = url.queryParameters['token_type'];
final providerToken = url.queryParameters['provider_token'];
final providerRefreshToken = url.queryParameters['provider_refresh_token'];
if (accessToken == null) {
throw AuthException('No access_token detected.');
}
if (expiresIn == null) {
throw AuthException('No expires_in detected.');
}
if (refreshToken == null) {
throw AuthException('No refresh_token detected.');
}
if (tokenType == null) {
throw AuthException('No token_type detected.');
}
final user = (await getUser(accessToken)).user;
if (user == null) {
throw AuthException('No user found.');
}
final session = Session(
providerToken: providerToken,
providerRefreshToken: providerRefreshToken,
accessToken: accessToken,
expiresIn: int.parse(expiresIn),
refreshToken: refreshToken,
tokenType: tokenType,
user: user,
);
final redirectType = url.queryParameters['type'];
if (storeSession == true) {
_saveSession(session);
if (redirectType == 'recovery') {
notifyAllSubscribers(AuthChangeEvent.passwordRecovery);
} else {
notifyAllSubscribers(AuthChangeEvent.signedIn);
}
}
return AuthSessionUrlResponse(session: session, redirectType: redirectType);
}
/// Signs out the current user, if there is a logged in user.
///
/// [scope] determines which sessions should be logged out.
///
/// If using [SignOutScope.others] scope, no [AuthChangeEvent.signedOut] event is fired!
Future<void> signOut({
SignOutScope scope = SignOutScope.local,
}) async {
_log.info('Signing out user with scope: $scope');
final accessToken = currentSession?.accessToken;
if (scope != SignOutScope.others) {
_removeSession();
await _asyncStorage?.removeItem(
key: '${Constants.defaultStorageKey}-code-verifier');
notifyAllSubscribers(AuthChangeEvent.signedOut);
}
if (accessToken != null) {
try {
await admin.signOut(accessToken, scope: scope);
} on AuthException catch (error) {
// ignore 401s since an invalid or expired JWT should sign out the current session
// ignore 403s since user might not exist anymore
// ignore 404s since user might not exist anymore
if (error.statusCode != '401' &&
error.statusCode != '403' &&
error.statusCode != '404') {
rethrow;
}
}
}
}
/// Sends a reset request to an email address.
Future<void> resetPasswordForEmail(
String email, {
String? redirectTo,
String? captchaToken,
}) async {
String? codeChallenge;
if (_flowType == AuthFlowType.pkce) {
assert(_asyncStorage != null,
'You need to provide asyncStorage to perform pkce flow.');
final codeVerifier = generatePKCEVerifier();
await _asyncStorage!.setItem(
key: '${Constants.defaultStorageKey}-code-verifier',
value: '$codeVerifier/${AuthChangeEvent.passwordRecovery.name}',
);
codeChallenge = generatePKCEChallenge(codeVerifier);
}
final body = {
'email': email,
'gotrue_meta_security': {'captcha_token': captchaToken},
'code_challenge': codeChallenge,
'code_challenge_method': codeChallenge != null ? 's256' : null,
};
final fetchOptions = GotrueRequestOptions(
headers: _headers,
body: body,
redirectTo: redirectTo,
);
await _fetch.request(
'$_url/recover',
RequestMethodType.post,
options: fetchOptions,
);
}
/// Gets all the identities linked to a user.
Future<List<UserIdentity>> getUserIdentities() async {
final res = await getUser();
return res.user?.identities ?? [];
}
/// Returns the URL to link the user's identity with an OAuth provider.
Future<OAuthResponse> getLinkIdentityUrl(
OAuthProvider provider, {
String? redirectTo,
String? scopes,
Map<String, String>? queryParams,
}) async {
final urlResponse = await _getUrlForProvider(
provider,
url: '$_url/user/identities/authorize',
redirectTo: redirectTo,
scopes: scopes,
queryParams: queryParams,
skipBrowserRedirect: true,
);
final res = await _fetch.request(urlResponse.url, RequestMethodType.get,
options: GotrueRequestOptions(
headers: _headers,
jwt: _currentSession?.accessToken,
));
return OAuthResponse(provider: provider, url: res['url']);
}
/// Unlinks an identity from a user by deleting it.
///
/// The user will no longer be able to sign in with that identity once it's unlinked.
Future<void> unlinkIdentity(UserIdentity identity) async {
await _fetch.request(
'$_url/user/identities/${identity.identityId}',
RequestMethodType.delete,
options: GotrueRequestOptions(
headers: headers,
jwt: _currentSession?.accessToken,
),
);
}
/// Set the initial session to the session obtained from local storage
Future<void> setInitialSession(String jsonStr) async {
final session = Session.fromJson(json.decode(jsonStr));
if (session == null) {
// sign out to delete the local storage from supabase_flutter
await signOut();
throw notifyException(AuthException('Initial session is missing data.'));
}
_currentSession = session;
_currentUser = session.user;
notifyAllSubscribers(AuthChangeEvent.initialSession);
}
/// Recover session from stringified [Session].
Future<AuthResponse> recoverSession(String jsonStr) async {
try {
final session = Session.fromJson(json.decode(jsonStr));
if (session == null) {
_log.warning("Can't recover session from string, session is null");
await signOut();
throw notifyException(
AuthException('Current session is missing data.'),
);
}
if (session.isExpired) {
_log.fine('Session from recovery is expired');
final refreshToken = session.refreshToken;
if (_autoRefreshToken && refreshToken != null) {
return await _callRefreshToken(refreshToken);
} else {
await signOut();
throw notifyException(AuthException('Session expired.'));
}
} else {
final shouldEmitEvent = _currentSession == null ||
_currentSession?.user.id != session.user.id;
_saveSession(session);
if (shouldEmitEvent) {