Skip to content

Commit

Permalink
Add debug logs to a lot of parts of the library
Browse files Browse the repository at this point in the history
  • Loading branch information
deepjyoti30-st committed Sep 27, 2024
1 parent 49c5ced commit b6ee6d4
Show file tree
Hide file tree
Showing 10 changed files with 59 additions and 41 deletions.
10 changes: 5 additions & 5 deletions lib/src/anti-csrf.dart
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ class AntiCSRF {
static String _sharedPreferencesKey = "supertokens-flutter-anti-csrf";

static Future<String?> getToken(String? associatedAccessTokenUpdate) async {
logDebugMessage('Getting token...')
logDebugMessage('associatedAccessTokenUpdate: ${associatedAccessTokenUpdate}')
logDebugMessage('Getting token');
logDebugMessage('associatedAccessTokenUpdate: ${associatedAccessTokenUpdate}');
if (associatedAccessTokenUpdate == null) {
AntiCSRF._antiCSRFInfo = null;
return null;
Expand Down Expand Up @@ -46,8 +46,8 @@ class AntiCSRF {

static Future<void> setToken(
String antiCSRFToken, String? associatedAccessTokenUpdate) async {
logDebugMessage('Setting token...')
logDebugMessage('associatedAccessTokenUpdate: ${associatedAccessTokenUpdate}')
logDebugMessage('Setting token');
logDebugMessage('associatedAccessTokenUpdate: ${associatedAccessTokenUpdate}');
if (associatedAccessTokenUpdate == null) {
AntiCSRF._antiCSRFInfo = null;
return;
Expand All @@ -63,7 +63,7 @@ class AntiCSRF {
}

static Future<void> removeToken() async {
logDebugMessage('Removing token...')
logDebugMessage('Removing token');
SharedPreferences preferences = await SharedPreferences.getInstance();
await preferences.remove(AntiCSRF._sharedPreferencesKey);
await preferences.reload();
Expand Down
28 changes: 14 additions & 14 deletions lib/src/cookie-store.dart
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,12 @@ class SuperTokensCookieStore {

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

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

logDebugMessage('Generated cookie uri: ${cookieUri}')
logDebugMessage('Generated cookie uri: ${cookieUri}');
return cookieUri;
}

/// Uses the [_allCookies] map to update values in shared preferences.
///
/// Strips expired cookies before storing in shared preferences
Future<void> _updatePersistentStorage() async {
logDebugMessage('Updating persistent storage with cookies...')
logDebugMessage('Updating persistent storage with cookies');
Map<String, List<String>> mapToStore = {};
_allCookies?.forEach((key, value) {
String uriString = key.toString();
Expand All @@ -131,12 +131,12 @@ class SuperTokensCookieStore {
///
/// 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.
Future<List<Cookie>> getForRequest(Uri uri) async {
logDebugMessage('Getting cookies for request from uri: ${uri}')
logDebugMessage('Getting cookies for request from uri: ${uri}');
List<Cookie> cookiesToReturn = [];
List<Cookie> allValidCookies = [];

if (_allCookies == null) {
logDebugMessage('No cookies found')
logDebugMessage('No cookies found');
return cookiesToReturn;
}

Expand Down Expand Up @@ -165,7 +165,7 @@ class SuperTokensCookieStore {
}
}

logDebugMessage('Total cookies found ${cookiesToReturn.length}')
logDebugMessage('Total cookies found ${cookiesToReturn.length}');
return cookiesToReturn;
}

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

Expand All @@ -204,7 +204,7 @@ class SuperTokensCookieStore {
///
/// Does not return expired cookies and will remove them from persistent storage if any are found.
Future<String> getCookieHeaderStringForRequest(Uri uri) async {
logDebugMessage('Getting cookie header for request from uri: ${uri}')
logDebugMessage('Getting cookie header for request from uri: ${uri}');
List<Cookie> cookies = await getForRequest(uri);
// ignore: unnecessary_null_comparison
if (cookies != null && cookies.isNotEmpty) {
Expand All @@ -227,7 +227,7 @@ class SuperTokensCookieStore {
///
/// Expired cookies are not saved.
Future<void> saveFromSetCookieHeader(Uri uri, String? setCookieHeader) async {
logDebugMessage('Saving cookie from header against uri: ${uri}')
logDebugMessage('Saving cookie from header against uri: ${uri}');
if (setCookieHeader != null) {
await saveFromResponse(uri, getCookieListFromHeader(setCookieHeader));
}
Expand All @@ -238,7 +238,7 @@ class SuperTokensCookieStore {
setCookieHeader.split(RegExp(r',(?=[^ ])'));
List<Cookie> setCookiesList =
setCookiesStringList.map((e) => Cookie.fromSetCookieValue(e)).toList();
logDebugMessage('Total cookies found in header: ${setCookiesList.length}')
logDebugMessage('Total cookies found in header: ${setCookiesList.length}');
return setCookiesList;
}
}
20 changes: 10 additions & 10 deletions lib/src/dio-interceptor-wrapper.dart
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ class SuperTokensInterceptorWrapper extends Interceptor {
@override
void onRequest(
RequestOptions options, RequestInterceptorHandler handler) async {
logDebugMessage('Intercepting request call')
logDebugMessage('Intercepting request call');
if (!SuperTokens.isInitCalled) {
handler.reject(DioException(
requestOptions: options,
Expand All @@ -35,13 +35,13 @@ class SuperTokensInterceptorWrapper extends Interceptor {
}

if (!shouldRunDioInterceptor(options)) {
logDebugMessage('Skipping dio interceptor')
logDebugMessage('Skipping dio interceptor');
return super.onRequest(options, handler);
}

logDebugMessage('Running dio interceptor')
logDebugMessage('Running dio interceptor');
if (Client.cookieStore == null) {
logDebugMessage('Initializing cookie store')
logDebugMessage('Initializing cookie store');
Client.cookieStore = SuperTokensCookieStore();
}

Expand Down Expand Up @@ -75,7 +75,7 @@ class SuperTokensInterceptorWrapper extends Interceptor {

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

@override
void onResponse(Response response, ResponseInterceptorHandler handler) async {
logDebugMessage('Intercepting response call')
logDebugMessage('Intercepting response call');
if (!shouldRunDioInterceptor(response.requestOptions)) {
logDebugMessage('Skipping dio interceptor')
logDebugMessage('Skipping dio interceptor');
return handler.next(response);
}

logDebugMessage('Running dio interceptor')
logDebugMessage('Running dio interceptor');
_refreshAPILock.acquireWrite();
await saveTokensFromHeaders(response);
String? frontTokenFromResponse =
Expand Down Expand Up @@ -132,7 +132,7 @@ class SuperTokensInterceptorWrapper extends Interceptor {
requestOptions.extra["__supertokensSessionRefreshAttempts"] ?? 0;
if (sessionRefreshAttempts >=
SuperTokens.config.maxRetryAttemptsForSessionRefresh) {
logDebugMessage('Max attempts of ${SuperTokens.config.maxRetryAttemptsForSessionRefresh} reached for refreshing, cannot continue')
logDebugMessage('Max attempts of ${SuperTokens.config.maxRetryAttemptsForSessionRefresh} reached for refreshing, cannot continue');
handler.reject(
DioException(
requestOptions: response.requestOptions,
Expand All @@ -150,7 +150,7 @@ class SuperTokensInterceptorWrapper extends Interceptor {
UnauthorisedResponse shouldRetry =
await Client.onUnauthorisedResponse(_preRequestLocalSessionState);
if (shouldRetry.status == UnauthorisedStatus.RETRY) {
logDebugMessage('Refreshing attempt: ${sessionRefreshAttempts + 1}')
logDebugMessage('Refreshing attempt: ${sessionRefreshAttempts + 1}');
requestOptions.headers[HttpHeaders.cookieHeader] = userSetCookie;

requestOptions.extra["__supertokensSessionRefreshAttempts"] =
Expand Down
4 changes: 4 additions & 0 deletions lib/src/front-token.dart
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import 'package:shared_preferences/shared_preferences.dart';
import 'package:supertokens_flutter/src/utilities.dart';
import 'package:supertokens_flutter/supertokens.dart';
import 'package:supertokens_flutter/src/anti-csrf.dart';
import 'package:supertokens_flutter/src/logger.dart';

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

if (frontToken == "remove") {
await FrontToken.removeToken();
Expand All @@ -127,6 +129,7 @@ class FrontToken {
}

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

static Future<void> removeToken() async {
logDebugMessage('Removing token');
await _tokenInfoMutex.acquireWrite();
await _removeTokenFromStorage();
await Utils.setToken(TokenType.ACCESS, "");
Expand Down
3 changes: 3 additions & 0 deletions lib/src/normalised-url-domain.dart
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import 'package:supertokens_flutter/src/errors.dart';
import 'package:supertokens_flutter/src/utilities.dart';
import 'package:supertokens_flutter/src/logger.dart';

class NormalisedURLDomain {
late String value;
Expand All @@ -12,6 +13,7 @@ class NormalisedURLDomain {
{bool ignoreProtocal = false}) {
String trimmedInput = input.trim();

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

logDebugMessage('Normalised value: ${trimmedInput}');
return trimmedInput;
} catch (e) {}

Expand Down
3 changes: 3 additions & 0 deletions lib/src/normalised-url-path.dart
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import 'package:supertokens_flutter/src/errors.dart';
import 'package:supertokens_flutter/src/logger.dart';

class NormalisedURLPath {
late String value;
Expand All @@ -8,6 +9,7 @@ class NormalisedURLPath {
}

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

try {
Expand All @@ -21,6 +23,7 @@ class NormalisedURLPath {
return trimmedInput.substring(0, trimmedInput.length - 1);
}

logDebugMessage('Normalised value: ${trimmedInput}');
return trimmedInput;
} catch (e) {}

Expand Down
9 changes: 8 additions & 1 deletion lib/src/supertokens-http-client.dart
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,13 @@ import 'package:supertokens_flutter/src/front-token.dart';
import 'package:supertokens_flutter/src/utilities.dart';
import 'package:supertokens_flutter/src/version.dart';
import 'package:supertokens_flutter/supertokens.dart';
import 'package:supertokens_flutter/src/logger.dart';

import 'constants.dart';

/// An [http.BaseClient] implementation for using SuperTokens for your network requests.
/// To make use of supertokens, use this as the client for making network calls instead of [http.Client] or your own custom clients.
/// 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.
/// 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.
ReadWriteMutex _refreshAPILock = ReadWriteMutex();

class CustomRequest {
Expand Down Expand Up @@ -48,6 +49,7 @@ class Client extends http.BaseClient {

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

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

if (SuperTokensUtils.getApiDomain(customRequest.request.url.toString()) ==
SuperTokens.refreshTokenUrl) {
logDebugMessage('Refresh token URL matched');
return _innerClient.send(customRequest.request);
}

if (!Utils.shouldDoInterceptions(
customRequest.request.url.toString(),
SuperTokens.config.apiDomain,
SuperTokens.config.sessionTokenBackendDomain)) {
logDebugMessage('Skipping interceptions');
return _innerClient.send(customRequest.request);
}

Expand Down Expand Up @@ -145,10 +150,12 @@ class Client extends http.BaseClient {
*/
if (customRequest.sessionRefreshAttempts >=
SuperTokens.config.maxRetryAttemptsForSessionRefresh) {
logDebugMessage('Max attempts of ${SuperTokens.config.maxRetryAttemptsForSessionRefresh} reached for refreshing, cannot continue');
throw SuperTokensException(
"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.");
}
customRequest.sessionRefreshAttempts++;
logDebugMessage('Refreshing attempt: ${customRequest.sessionRefreshAttempts}');

customRequest.request =
await _removeAuthHeaderIfMatchesLocalToken(copiedRequest);
Expand Down
Loading

0 comments on commit b6ee6d4

Please sign in to comment.