Skip to content

Commit

Permalink
refactor(neon_http_client): use nextcloud csrf request
Browse files Browse the repository at this point in the history
Signed-off-by: Nikolas Rimikis <[email protected]>
  • Loading branch information
Leptopoda committed Sep 18, 2024
1 parent 3d57b72 commit 74fd815
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 12 deletions.
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
import 'dart:convert';

import 'package:http/http.dart' as http;
import 'package:interceptor_http_client/interceptor_http_client.dart';
import 'package:logging/logging.dart';
import 'package:meta/meta.dart';
import 'package:nextcloud/nextcloud.dart';
import 'package:nextcloud/core.dart' as core;
import 'package:nextcloud/webdav.dart' as webdav;

/// A HttpInterceptor that works around a Nextcloud CSRF bug when cookies are sent.
Expand All @@ -25,10 +23,15 @@ final class CSRFInterceptor implements HttpInterceptor {
CSRFInterceptor({
required http.Client client,
required Uri baseURL,
}) : _client = client,
}) : _client = core
.$Client(
baseURL,
httpClient: client,
)
.csrfToken,
_baseURL = baseURL;

final http.Client _client;
final core.$CsrfTokenClient _client;

final Uri _baseURL;

Expand Down Expand Up @@ -57,12 +60,8 @@ final class CSRFInterceptor implements HttpInterceptor {
if (token == null) {
_log.fine('Acquiring new CSRF token for WebDAV');

final response = await _client.get(Uri.parse('$_baseURL/index.php/csrftoken'));
if (response.statusCode >= 300) {
throw DynamiteStatusCodeException(response);
}

token = (json.decode(response.body) as Map<String, dynamic>)['token']! as String;
final response = await _client.index();
token = response.body.token;
}

request.headers.addAll({
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import 'dart:io';

import 'package:http/http.dart';
import 'package:http/testing.dart';
import 'package:mocktail/mocktail.dart';
Expand Down Expand Up @@ -56,7 +58,13 @@ void main() {

test('requests and attaches a new token', () async {
final mockedClient = MockClient((request) async {
return Response('{"token":"token"}', 200);
return Response(
'{"token":"token"}',
200,
headers: {
HttpHeaders.contentTypeHeader: 'application/json',
},
);
});

final interceptor = CSRFInterceptor(
Expand Down

0 comments on commit 74fd815

Please sign in to comment.