onRequest method
void
onRequest(- dynamic options,
- dynamic handler
)
Implementation
@override
void onRequest(
RequestOptions options, RequestInterceptorHandler handler) async {
if (!SuperTokens.isInitCalled) {
handler.reject(DioException(
requestOptions: options,
type: DioExceptionType.unknown,
error: SuperTokensException(
"SuperTokens.init must be called before using Client"),
));
return;
}
if (!shouldRunDioInterceptor(options)) {
return super.onRequest(options, handler);
}
if (Client.cookieStore == null) {
Client.cookieStore = SuperTokensCookieStore();
}
options = await _removeAuthHeaderIfMatchesLocalToken(options);
_preRequestLocalSessionState =
await SuperTokensUtils.getLocalSessionState();
String? antiCSRFToken = await AntiCSRF.getToken(
_preRequestLocalSessionState.lastAccessTokenUpdate);
if (antiCSRFToken != null) {
options.headers[antiCSRFHeaderKey] = antiCSRFToken;
}
SuperTokensTokenTransferMethod tokenTransferMethod =
SuperTokens.config.tokenTransferMethod;
options.headers["st-auth-mode"] = tokenTransferMethod.getValue();
options = await _setAuthorizationHeaderIfRequired(options);
userSetCookie = options.headers[HttpHeaders.cookieHeader];
String uriForCookieString = options.uri.toString();
if (!uriForCookieString.endsWith("/")) {
uriForCookieString += "/";
}
String? newCookiesToAdd = await Client.cookieStore
?.getCookieHeaderStringForRequest(Uri.parse(uriForCookieString));
String? existingCookieHeader = options.headers[HttpHeaders.cookieHeader];
// If the request already has a "cookie" header, combine it with persistent cookies
if (existingCookieHeader != null) {
options.headers[HttpHeaders.cookieHeader] =
"$existingCookieHeader;${newCookiesToAdd ?? ""}";
} else {
options.headers[HttpHeaders.cookieHeader] = newCookiesToAdd ?? "";
}
var oldValidate = options.validateStatus;
options.validateStatus = (status) {
if (status != null &&
status == SuperTokens.config.sessionExpiredStatusCode) {
return true;
}
return oldValidate(status);
};
handler.next(options);
}