Skip to content

Commit

Permalink
feat(nextcloud): migrate webdav to DynamiteClient.sendWithCookies
Browse files Browse the repository at this point in the history
Signed-off-by: Nikolas Rimikis <leptopoda@users.noreply.github.com>
  • Loading branch information
Leptopoda committed Apr 2, 2024
1 parent 3e259ba commit 67a122a
Showing 1 changed file with 15 additions and 21 deletions.
36 changes: 15 additions & 21 deletions packages/nextcloud/lib/src/webdav/csrf_client.dart
Original file line number Diff line number Diff line change
@@ -1,16 +1,12 @@
import 'package:dynamite_runtime/http_client.dart';
import 'package:http/http.dart' as http;

// ignore: do_not_use_environment
const bool _kIsWeb = bool.fromEnvironment('dart.library.js_util');

/// A [http.Client] that sends the Nextcloud CSRF token.
///
/// {@template WebDavCSRFClient}
/// On web we need to send a CSRF token because we also send the cookies. In theory this should not be required as
/// When sending a request with cookies a CSRF token is also needed. In theory this should not be required as
/// long as we send the OCS-APIRequest header, but the server has a bug that only triggers when you also send the
/// cookies. On non-web platforms we don't send the cookies so we are fine, but on web the browser always does it
/// and therefore we need this workaround.
/// cookies.
/// {@endtemplate}
final class WebDavCSRFClient with http.BaseClient {
/// Creates a new CSRF client that executes requests through the given [DynamiteClient].
Expand All @@ -23,25 +19,23 @@ final class WebDavCSRFClient with http.BaseClient {

@override
Future<http.StreamedResponse> send(http.BaseRequest request) async {
if (_kIsWeb) {
if (_token == null) {
final response = await _inner.get(Uri.parse('${_inner.baseURL}/index.php'));
if (response.statusCode >= 300) {
throw DynamiteStatusCodeException(
response.statusCode,
);
}

_token = RegExp('data-requesttoken="([^"]*)"').firstMatch(response.body)!.group(1);
if (_token == null) {
final response = await _inner.get(Uri.parse('${_inner.baseURL}/index.php'));
if (response.statusCode >= 300) {
throw DynamiteStatusCodeException(
response.statusCode,
);
}

request.headers.addAll({
'OCS-APIRequest': 'true',
'requesttoken': _token!,
});
_token = RegExp('data-requesttoken="([^"]*)"').firstMatch(response.body)!.group(1);
}

final response = await _inner.send(request);
request.headers.addAll({
'OCS-APIRequest': 'true',
'requesttoken': _token!,
});

final response = await _inner.sendWithCookies(request);

if (response.statusCode >= 300) {
throw DynamiteStatusCodeException(
Expand Down

0 comments on commit 67a122a

Please sign in to comment.