Files
notifications-admin/app/assets/javascripts/registerSecurityKey.js
Leo Hemsted 0b27d7e0a9 show error message in banner rather than an alert
the banner is a nicer user experience, and consistent with how we
display errors elsewhere in notify. For now pass through the error
message from JS, but we'll probably want to change that since the erorr
messages themselves are often a bit cryptic and unhelpful
2021-09-14 18:43:26 +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('Something went wrong');
});
});
};
};
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);