53 lines
2.1 KiB
Twig
53 lines
2.1 KiB
Twig
<script>
|
|
const form = document.getElementById('preauth-form');
|
|
const message = document.getElementById('preauth-message');
|
|
|
|
form.addEventListener('submit', (event) => {
|
|
event.preventDefault();
|
|
|
|
/* make base64url string containing our payload json object */
|
|
const data = btoa(JSON.stringify({
|
|
id: form.preauth_id.value,
|
|
token: form.preauth_token.value,
|
|
nonce: form.preauth_nonce.value,
|
|
json: true
|
|
})).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
|
|
|
/* send our request to the server */
|
|
fetch(window.location.href, {
|
|
method: 'GET',
|
|
headers: { 'X-Preauth': data },
|
|
}).then((response) => {
|
|
if (response.headers.has('Location')) {
|
|
/* follow redirect (not needed in most browsers) */
|
|
window.location.href = response.headers.get('Location');
|
|
} else if (response.headers.get('Content-Type') === 'application/json') {
|
|
/* got json, update the page */
|
|
response.json().then((content) => {
|
|
if (Object.hasOwn(content, 'message')) {
|
|
message.innerText = content.message;
|
|
}
|
|
if (Object.hasOwn(content, 'nonce')) {
|
|
form.preauth_nonce.value = content.nonce;
|
|
form.preauth_token.value = '';
|
|
form.preauth_token.focus();
|
|
}
|
|
}).catch((error) => {
|
|
console.log('failed to parse json from response');
|
|
console.log(error);
|
|
});
|
|
} else { /* non-json, non-redirect response */
|
|
/* overwrite the page */
|
|
response.text().then((text) => {
|
|
document.open();
|
|
document.write(text);
|
|
document.close();
|
|
}).catch((error) => {
|
|
console.log('failed to get text from response');
|
|
console.log(error);
|
|
});
|
|
}
|
|
});
|
|
});
|
|
</script>
|