Switch to window.fetch for AJAX calls

In response to [1]. Using window.fetch means we don't get console
logs on errors, so this simplifies the error handling, although we
need to account for some errors not being a standard error object,
such as the string we get by doing Promise.reject('error').

In making this change, I've also started addressing another comment
in the PR [2], so that we reset mocked objects after the tests.

This also switches the ordering of done(), so that it's the last
statement (in response to [3]).

In the next commit we'll check for 'response.ok', but I wanted to
keep this one simple, as it's quite a large change.

[1]: https://github.com/alphagov/notifications-admin/pull/3878#discussion_r631054187
[2]: https://github.com/alphagov/notifications-admin/pull/3878#discussion_r631060116
[3]: https://github.com/alphagov/notifications-admin/pull/3878#discussion_r631061628
This commit is contained in:
Ben Thorner
2021-05-12 17:06:54 +01:00
parent 957dba4356
commit 6948f5f003
2 changed files with 38 additions and 44 deletions

View File

@@ -7,7 +7,10 @@
.on('click', function(event) {
event.preventDefault();
fetchWebAuthnCreateOptions()
fetch('/webauthn/register')
.then((response) => {
return response.arrayBuffer();
})
.then((data) => {
var options = window.CBOR.decode(data);
// triggers browser dialogue to select authenticator
@@ -22,45 +25,21 @@
window.location.reload();
})
.catch((error) => {
// there may be other kinds of error we should catch here
// https://github.com/w3c/webauthn/issues/876
if (error instanceof DOMException) {
console.error(error);
// not all browsers show an error dialogue, so to be safe
// we manually pop one open here (to be improved in future!)
alert('Error communicating with device.\n\n' + error.message);
} else {
// for web requests we need to manually alert the user
// $.ajax seems to log by itself, but that's not visible
alert('Error during registration. Please try again.');
}
console.error(error);
// some browsers will show an error dialogue for some
// errors; to be safe we always pop up an alert
var message = error.message || error;
alert('Error during registration.\n\n' + message);
});
});
};
};
function fetchWebAuthnCreateOptions() {
var xhrOverride = new XMLHttpRequest();
xhrOverride.responseType = 'arraybuffer';
return $.ajax({
url: '/webauthn/register',
xhr: () => xhrOverride,
dataType: 'x-binary',
converters: { '* x-binary': (value) => value }
});
}
function postWebAuthnCreateResponse(response, csrf_token) {
return $.ajax({
url: '/webauthn/register',
return fetch('/webauthn/register', {
method: 'POST',
headers: {
'X-CSRFToken': csrf_token
},
processData: false,
contentType: 'application/cbor',
data: window.CBOR.encode({
headers: { 'X-CSRFToken': csrf_token },
body: window.CBOR.encode({
attestationObject: new Uint8Array(response.attestationObject),
clientDataJSON: new Uint8Array(response.clientDataJSON),
})