Files
notifications-admin/app/assets/javascripts/registerSecurityKey.js
Leo Hemsted 2c55f4d0ce hard-code html error message for errorBanner
turns out that we're only using errorBanner with a static message, and
it's also full of rich html content. This means that it's probably
better to put it in the html templates with other content, rather than
hidden away in js files if we can help it.

Since there are two places, had to dupe the error message but i think
that's fine as i don't anticipate this error message being used in
significantly more places.

making it a string is a bit gross and means we don't get nice syntax
highlighting on it, but as it needs to be passed in to a jinja macro
that's the way it has to go unfortunately.
2021-09-14 18:43:27 +01:00

69 lines
2.2 KiB
JavaScript

(function(window) {
"use strict";
window.GOVUK.Modules.RegisterSecurityKey = function() {
this.start = function(component) {
$(component)
.on('click', function(event) {
event.preventDefault();
// hide any existing error prompt
window.GOVUK.ErrorBanner.hideBanner();
fetch('/webauthn/register')
.then((response) => {
if (!response.ok) {
throw Error(response.statusText);
}
return response.arrayBuffer();
})
.then((data) => {
var options = window.CBOR.decode(data);
// triggers browser dialogue to select authenticator
return window.navigator.credentials.create(options);
})
.then((credential) => {
return postWebAuthnCreateResponse(
credential.response, component.data('csrfToken')
);
})
.then((response) => {
if (!response.ok) {
return response.arrayBuffer()
.then((cbor) => {
return Promise.resolve(window.CBOR.decode(cbor));
})
.catch(() => {
throw Error(response.statusText);
})
.then((text) => {
throw Error(text);
});
}
window.location.reload();
})
.catch((error) => {
console.error(error);
// some browsers will show an error dialogue for some
// errors; to be safe we always display an error message on the page.
const message = error.message || error;
window.GOVUK.ErrorBanner.showBanner();
});
});
};
};
function postWebAuthnCreateResponse(response, csrf_token) {
return fetch('/webauthn/register', {
method: 'POST',
headers: { 'X-CSRFToken': csrf_token },
body: window.CBOR.encode({
attestationObject: new Uint8Array(response.attestationObject),
clientDataJSON: new Uint8Array(response.clientDataJSON),
})
});
}
})(window);