Skip to content

Commit b6ee6d4

Browse files
Add debug logs to a lot of parts of the library
1 parent 49c5ced commit b6ee6d4

10 files changed

+59
-41
lines changed

lib/src/anti-csrf.dart

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,8 @@ class AntiCSRF {
1616
static String _sharedPreferencesKey = "supertokens-flutter-anti-csrf";
1717

1818
static Future<String?> getToken(String? associatedAccessTokenUpdate) async {
19-
logDebugMessage('Getting token...')
20-
logDebugMessage('associatedAccessTokenUpdate: ${associatedAccessTokenUpdate}')
19+
logDebugMessage('Getting token');
20+
logDebugMessage('associatedAccessTokenUpdate: ${associatedAccessTokenUpdate}');
2121
if (associatedAccessTokenUpdate == null) {
2222
AntiCSRF._antiCSRFInfo = null;
2323
return null;
@@ -46,8 +46,8 @@ class AntiCSRF {
4646

4747
static Future<void> setToken(
4848
String antiCSRFToken, String? associatedAccessTokenUpdate) async {
49-
logDebugMessage('Setting token...')
50-
logDebugMessage('associatedAccessTokenUpdate: ${associatedAccessTokenUpdate}')
49+
logDebugMessage('Setting token');
50+
logDebugMessage('associatedAccessTokenUpdate: ${associatedAccessTokenUpdate}');
5151
if (associatedAccessTokenUpdate == null) {
5252
AntiCSRF._antiCSRFInfo = null;
5353
return;
@@ -63,7 +63,7 @@ class AntiCSRF {
6363
}
6464

6565
static Future<void> removeToken() async {
66-
logDebugMessage('Removing token...')
66+
logDebugMessage('Removing token');
6767
SharedPreferences preferences = await SharedPreferences.getInstance();
6868
await preferences.remove(AntiCSRF._sharedPreferencesKey);
6969
await preferences.reload();

lib/src/cookie-store.dart

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -25,12 +25,12 @@ class SuperTokensCookieStore {
2525

2626
/// Loads all cookies stored in shared preferences into the in memory map [_allCookies]
2727
static Future<void> _loadFromPersistence() async {
28-
logDebugMessage('Trying to load cookies from memory')
28+
logDebugMessage('Trying to load cookies from memory');
2929
_allCookies = {};
3030
String cookiesStringInStorage =
3131
_sharedPreferences?.getString(_cookieSharedPrefsKey) ?? "{}";
3232
Map<String, dynamic> cookiesInStorage = jsonDecode(cookiesStringInStorage);
33-
logDebugMessage('cookies found: ${jsonEncode(cookiesInStorage)}')
33+
logDebugMessage('cookies found: ${jsonEncode(cookiesInStorage)}');
3434
cookiesInStorage.forEach((key, value) {
3535
Uri uri = Uri.parse(key);
3636
List<String> cookieStrings = List.from(value);
@@ -52,8 +52,8 @@ class SuperTokensCookieStore {
5252
///
5353
/// If you are trying to store cookies from a "set-cookie" header response, consider using the [saveFromSetCookieHeader] utility method which parses the header string.
5454
Future<void> saveFromResponse(Uri uri, List<Cookie> cookies) async {
55-
logDebugMessage('Saving cookies against: ${uri}')
56-
logDebugMessage('Passed cookies: ${jsonEncode(cookies)}')
55+
logDebugMessage('Saving cookies against: ${uri}');
56+
logDebugMessage('Passed cookies: ${jsonEncode(cookies)}');
5757
await Future.forEach<Cookie>(cookies, (element) async {
5858
Uri uriToStore = await _getCookieUri(uri, element);
5959
List<Cookie> currentCookies = _allCookies?[uriToStore] ?? List.from([]);
@@ -81,7 +81,7 @@ class SuperTokensCookieStore {
8181

8282
/// Returns a Uri to use when saving the cookie
8383
Future<Uri> _getCookieUri(Uri requestUri, Cookie cookie) async {
84-
logDebugMessage('Creating cookie uri from: ${requestUri}')
84+
logDebugMessage('Creating cookie uri from: ${requestUri}');
8585
Uri cookieUri = Uri.parse(
8686
// ignore: unnecessary_null_comparison
8787
"${requestUri.scheme == null ? "http" : requestUri.scheme}://${requestUri.host}${cookie.path == null ? "" : cookie.path}");
@@ -104,15 +104,15 @@ class SuperTokensCookieStore {
104104
}
105105
}
106106

107-
logDebugMessage('Generated cookie uri: ${cookieUri}')
107+
logDebugMessage('Generated cookie uri: ${cookieUri}');
108108
return cookieUri;
109109
}
110110

111111
/// Uses the [_allCookies] map to update values in shared preferences.
112112
///
113113
/// Strips expired cookies before storing in shared preferences
114114
Future<void> _updatePersistentStorage() async {
115-
logDebugMessage('Updating persistent storage with cookies...')
115+
logDebugMessage('Updating persistent storage with cookies');
116116
Map<String, List<String>> mapToStore = {};
117117
_allCookies?.forEach((key, value) {
118118
String uriString = key.toString();
@@ -131,12 +131,12 @@ class SuperTokensCookieStore {
131131
///
132132
/// If you are trying to add cookies to a "cookie" header for a network call, consider using the [getCookieHeaderStringForRequest] which creates a semi-colon separated cookie string for a given Uri.
133133
Future<List<Cookie>> getForRequest(Uri uri) async {
134-
logDebugMessage('Getting cookies for request from uri: ${uri}')
134+
logDebugMessage('Getting cookies for request from uri: ${uri}');
135135
List<Cookie> cookiesToReturn = [];
136136
List<Cookie> allValidCookies = [];
137137

138138
if (_allCookies == null) {
139-
logDebugMessage('No cookies found')
139+
logDebugMessage('No cookies found');
140140
return cookiesToReturn;
141141
}
142142

@@ -165,7 +165,7 @@ class SuperTokensCookieStore {
165165
}
166166
}
167167

168-
logDebugMessage('Total cookies found ${cookiesToReturn.length}')
168+
logDebugMessage('Total cookies found ${cookiesToReturn.length}');
169169
return cookiesToReturn;
170170
}
171171

@@ -186,7 +186,7 @@ class SuperTokensCookieStore {
186186
/// Removes a list of cookies from persistent storage
187187
Future<void> _removeFromPersistence(
188188
Uri uri, List<Cookie> cookiesToRemove) async {
189-
logDebugMessage('Removing cookies from persistent storage...')
189+
logDebugMessage('Removing cookies from persistent storage');
190190
List<Cookie> _cookiesToRemove = List.from(cookiesToRemove);
191191
List<Cookie> currentCookies = _allCookies?[uri] ?? List.from([]);
192192

@@ -204,7 +204,7 @@ class SuperTokensCookieStore {
204204
///
205205
/// Does not return expired cookies and will remove them from persistent storage if any are found.
206206
Future<String> getCookieHeaderStringForRequest(Uri uri) async {
207-
logDebugMessage('Getting cookie header for request from uri: ${uri}')
207+
logDebugMessage('Getting cookie header for request from uri: ${uri}');
208208
List<Cookie> cookies = await getForRequest(uri);
209209
// ignore: unnecessary_null_comparison
210210
if (cookies != null && cookies.isNotEmpty) {
@@ -227,7 +227,7 @@ class SuperTokensCookieStore {
227227
///
228228
/// Expired cookies are not saved.
229229
Future<void> saveFromSetCookieHeader(Uri uri, String? setCookieHeader) async {
230-
logDebugMessage('Saving cookie from header against uri: ${uri}')
230+
logDebugMessage('Saving cookie from header against uri: ${uri}');
231231
if (setCookieHeader != null) {
232232
await saveFromResponse(uri, getCookieListFromHeader(setCookieHeader));
233233
}
@@ -238,7 +238,7 @@ class SuperTokensCookieStore {
238238
setCookieHeader.split(RegExp(r',(?=[^ ])'));
239239
List<Cookie> setCookiesList =
240240
setCookiesStringList.map((e) => Cookie.fromSetCookieValue(e)).toList();
241-
logDebugMessage('Total cookies found in header: ${setCookiesList.length}')
241+
logDebugMessage('Total cookies found in header: ${setCookiesList.length}');
242242
return setCookiesList;
243243
}
244244
}

lib/src/dio-interceptor-wrapper.dart

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ class SuperTokensInterceptorWrapper extends Interceptor {
2323
@override
2424
void onRequest(
2525
RequestOptions options, RequestInterceptorHandler handler) async {
26-
logDebugMessage('Intercepting request call')
26+
logDebugMessage('Intercepting request call');
2727
if (!SuperTokens.isInitCalled) {
2828
handler.reject(DioException(
2929
requestOptions: options,
@@ -35,13 +35,13 @@ class SuperTokensInterceptorWrapper extends Interceptor {
3535
}
3636

3737
if (!shouldRunDioInterceptor(options)) {
38-
logDebugMessage('Skipping dio interceptor')
38+
logDebugMessage('Skipping dio interceptor');
3939
return super.onRequest(options, handler);
4040
}
4141

42-
logDebugMessage('Running dio interceptor')
42+
logDebugMessage('Running dio interceptor');
4343
if (Client.cookieStore == null) {
44-
logDebugMessage('Initializing cookie store')
44+
logDebugMessage('Initializing cookie store');
4545
Client.cookieStore = SuperTokensCookieStore();
4646
}
4747

@@ -75,7 +75,7 @@ class SuperTokensInterceptorWrapper extends Interceptor {
7575

7676
// If the request already has a "cookie" header, combine it with persistent cookies
7777
if (existingCookieHeader != null) {
78-
logDebugMessage('Combining cookie header values')
78+
logDebugMessage('Combining cookie header values');
7979
options.headers[HttpHeaders.cookieHeader] =
8080
"$existingCookieHeader;${newCookiesToAdd ?? ""}";
8181
} else {
@@ -96,13 +96,13 @@ class SuperTokensInterceptorWrapper extends Interceptor {
9696

9797
@override
9898
void onResponse(Response response, ResponseInterceptorHandler handler) async {
99-
logDebugMessage('Intercepting response call')
99+
logDebugMessage('Intercepting response call');
100100
if (!shouldRunDioInterceptor(response.requestOptions)) {
101-
logDebugMessage('Skipping dio interceptor')
101+
logDebugMessage('Skipping dio interceptor');
102102
return handler.next(response);
103103
}
104104

105-
logDebugMessage('Running dio interceptor')
105+
logDebugMessage('Running dio interceptor');
106106
_refreshAPILock.acquireWrite();
107107
await saveTokensFromHeaders(response);
108108
String? frontTokenFromResponse =
@@ -132,7 +132,7 @@ class SuperTokensInterceptorWrapper extends Interceptor {
132132
requestOptions.extra["__supertokensSessionRefreshAttempts"] ?? 0;
133133
if (sessionRefreshAttempts >=
134134
SuperTokens.config.maxRetryAttemptsForSessionRefresh) {
135-
logDebugMessage('Max attempts of ${SuperTokens.config.maxRetryAttemptsForSessionRefresh} reached for refreshing, cannot continue')
135+
logDebugMessage('Max attempts of ${SuperTokens.config.maxRetryAttemptsForSessionRefresh} reached for refreshing, cannot continue');
136136
handler.reject(
137137
DioException(
138138
requestOptions: response.requestOptions,
@@ -150,7 +150,7 @@ class SuperTokensInterceptorWrapper extends Interceptor {
150150
UnauthorisedResponse shouldRetry =
151151
await Client.onUnauthorisedResponse(_preRequestLocalSessionState);
152152
if (shouldRetry.status == UnauthorisedStatus.RETRY) {
153-
logDebugMessage('Refreshing attempt: ${sessionRefreshAttempts + 1}')
153+
logDebugMessage('Refreshing attempt: ${sessionRefreshAttempts + 1}');
154154
requestOptions.headers[HttpHeaders.cookieHeader] = userSetCookie;
155155

156156
requestOptions.extra["__supertokensSessionRefreshAttempts"] =

lib/src/front-token.dart

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import 'package:shared_preferences/shared_preferences.dart';
55
import 'package:supertokens_flutter/src/utilities.dart';
66
import 'package:supertokens_flutter/supertokens.dart';
77
import 'package:supertokens_flutter/src/anti-csrf.dart';
8+
import 'package:supertokens_flutter/src/logger.dart';
89

910
class FrontToken {
1011
static String? tokenInMemory;
@@ -110,6 +111,7 @@ class FrontToken {
110111
// Check the start and end of onUnauthorisedResponse
111112
// As a side-effect we reload the anti-csrf token to check if it was changed by another tab.
112113
await SuperTokensUtils.saveLastAccessTokenUpdate();
114+
logDebugMessage('Setting front token');
113115

114116
if (frontToken == "remove") {
115117
await FrontToken.removeToken();
@@ -127,6 +129,7 @@ class FrontToken {
127129
}
128130

129131
static Future<bool> doesTokenExist() async {
132+
logDebugMessage('Checking if token exists');
130133
try {
131134
await _frontTokenMutex.acquire();
132135
var frontToken = await FrontToken._getFronTokenFromStorage();
@@ -145,6 +148,7 @@ class FrontToken {
145148
}
146149

147150
static Future<void> removeToken() async {
151+
logDebugMessage('Removing token');
148152
await _tokenInfoMutex.acquireWrite();
149153
await _removeTokenFromStorage();
150154
await Utils.setToken(TokenType.ACCESS, "");

lib/src/normalised-url-domain.dart

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import 'package:supertokens_flutter/src/errors.dart';
22
import 'package:supertokens_flutter/src/utilities.dart';
3+
import 'package:supertokens_flutter/src/logger.dart';
34

45
class NormalisedURLDomain {
56
late String value;
@@ -12,6 +13,7 @@ class NormalisedURLDomain {
1213
{bool ignoreProtocal = false}) {
1314
String trimmedInput = input.trim();
1415

16+
logDebugMessage('Normalising url domain: ${input}');
1517
try {
1618
if (!trimmedInput.startsWith("http://") &&
1719
!trimmedInput.startsWith("https://")) {
@@ -35,6 +37,7 @@ class NormalisedURLDomain {
3537
trimmedInput = scheme + "://" + hostSuffix;
3638
}
3739

40+
logDebugMessage('Normalised value: ${trimmedInput}');
3841
return trimmedInput;
3942
} catch (e) {}
4043

lib/src/normalised-url-path.dart

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import 'package:supertokens_flutter/src/errors.dart';
2+
import 'package:supertokens_flutter/src/logger.dart';
23

34
class NormalisedURLPath {
45
late String value;
@@ -8,6 +9,7 @@ class NormalisedURLPath {
89
}
910

1011
static String normaliseIRLPathOrThrowError(String input) {
12+
logDebugMessage('Normalising URL path: ${input}');
1113
String trimmedInput = input.trim();
1214

1315
try {
@@ -21,6 +23,7 @@ class NormalisedURLPath {
2123
return trimmedInput.substring(0, trimmedInput.length - 1);
2224
}
2325

26+
logDebugMessage('Normalised value: ${trimmedInput}');
2427
return trimmedInput;
2528
} catch (e) {}
2629

lib/src/supertokens-http-client.dart

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,12 +9,13 @@ import 'package:supertokens_flutter/src/front-token.dart';
99
import 'package:supertokens_flutter/src/utilities.dart';
1010
import 'package:supertokens_flutter/src/version.dart';
1111
import 'package:supertokens_flutter/supertokens.dart';
12+
import 'package:supertokens_flutter/src/logger.dart';
1213

1314
import 'constants.dart';
1415

1516
/// An [http.BaseClient] implementation for using SuperTokens for your network requests.
1617
/// To make use of supertokens, use this as the client for making network calls instead of [http.Client] or your own custom clients.
17-
/// If you use a custom client for your network calls pass an instance of it as a paramter when initialising [Client], pass [http.Client()] to use the default.
18+
/// If you use a custom client for your network calls pass an instance of it as a parameter when initialising [Client], pass [http.Client()] to use the default.
1819
ReadWriteMutex _refreshAPILock = ReadWriteMutex();
1920

2021
class CustomRequest {
@@ -48,6 +49,7 @@ class Client extends http.BaseClient {
4849

4950
Future<http.StreamedResponse> _sendWithRetry(
5051
CustomRequest customRequest) async {
52+
logDebugMessage('Sending request');
5153
if (Client.cookieStore == null) {
5254
Client.cookieStore = SuperTokensCookieStore();
5355
}
@@ -59,18 +61,21 @@ class Client extends http.BaseClient {
5961

6062
if (SuperTokensUtils.getApiDomain(customRequest.request.url.toString()) !=
6163
SuperTokens.config.apiDomain) {
64+
logDebugMessage('Not matching api domain, using inner client');
6265
return _innerClient.send(customRequest.request);
6366
}
6467

6568
if (SuperTokensUtils.getApiDomain(customRequest.request.url.toString()) ==
6669
SuperTokens.refreshTokenUrl) {
70+
logDebugMessage('Refresh token URL matched');
6771
return _innerClient.send(customRequest.request);
6872
}
6973

7074
if (!Utils.shouldDoInterceptions(
7175
customRequest.request.url.toString(),
7276
SuperTokens.config.apiDomain,
7377
SuperTokens.config.sessionTokenBackendDomain)) {
78+
logDebugMessage('Skipping interceptions');
7479
return _innerClient.send(customRequest.request);
7580
}
7681

@@ -145,10 +150,12 @@ class Client extends http.BaseClient {
145150
*/
146151
if (customRequest.sessionRefreshAttempts >=
147152
SuperTokens.config.maxRetryAttemptsForSessionRefresh) {
153+
logDebugMessage('Max attempts of ${SuperTokens.config.maxRetryAttemptsForSessionRefresh} reached for refreshing, cannot continue');
148154
throw SuperTokensException(
149155
"Received a 401 response from ${customRequest.request.url}. Attempted to refresh the session and retry the request with the updated session tokens ${SuperTokens.config.maxRetryAttemptsForSessionRefresh} times, but each attempt resulted in a 401 error. The maximum session refresh limit has been reached. Please investigate your API. To increase the session refresh attempts, update maxRetryAttemptsForSessionRefresh in the config.");
150156
}
151157
customRequest.sessionRefreshAttempts++;
158+
logDebugMessage('Refreshing attempt: ${customRequest.sessionRefreshAttempts}');
152159

153160
customRequest.request =
154161
await _removeAuthHeaderIfMatchesLocalToken(copiedRequest);

0 commit comments

Comments
 (0)