-
Notifications
You must be signed in to change notification settings - Fork 32
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #1853 from nextcloud/feat/nextcloud/webdav_http_cl…
…ient feat(nextcloud): add http.Client that handles the CSRF token for webd…
- Loading branch information
Showing
2 changed files
with
65 additions
and
54 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,48 @@ | ||
import 'package:dynamite_runtime/http_client.dart'; | ||
import 'package:http/http.dart' as http; | ||
|
||
/// A [http.Client] that sends the Nextcloud CSRF token. | ||
/// | ||
/// {@template WebDavCSRFClient} | ||
/// 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. | ||
/// {@endtemplate} | ||
final class WebDavCSRFClient with http.BaseClient { | ||
/// Creates a new CSRF client that executes requests through the given [DynamiteClient]. | ||
WebDavCSRFClient(this._inner); | ||
|
||
final DynamiteClient _inner; | ||
|
||
/// The request token sent by the [WebDavCSRFClient]. | ||
String? _token; | ||
|
||
@override | ||
Future<http.StreamedResponse> send(http.BaseRequest request) async { | ||
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); | ||
} | ||
|
||
request.headers.addAll({ | ||
'OCS-APIRequest': 'true', | ||
'requesttoken': _token!, | ||
}); | ||
|
||
final response = await _inner.sendWithCookies(request); | ||
|
||
if (response.statusCode >= 300) { | ||
throw DynamiteStatusCodeException( | ||
response.statusCode, | ||
); | ||
} | ||
|
||
return response; | ||
} | ||
} |