

up.compiler('#webauthn_login', function (element, params) {
    "use strict";
    const { startAuthentication } = SimpleWebAuthnBrowser;

    // <button>
    const elemBegin = document.getElementById('btn_webauthn_begin');
    const elemError = document.getElementById('btn_webauthn_error');


    // Start authentication when the user clicks a button
    elemBegin.addEventListener('click', async () => {
        // Reset success/error messages

        // GET authentication options from the endpoint that calls
        // @simplewebauthn/server -> generateAuthenticationOptions()
        const resp = params.authentication_options;

        let assertionResp;
        try {
          // Pass the options to the authenticator and wait for a response
          assertionResp = await startAuthentication(resp);
        } catch (error) {
          throw error;
        }

        // POST the response to the endpoint that calls
        // @simplewebauthn/server -> verifyAuthenticationResponse()
        const verificationResp = await fetch(params.verification_url, {
          method: 'POST',
          headers: {
              'Content-Type': 'application/json',
              'X-CSRFToken': params.csrf_token,
          },
          body: JSON.stringify(assertionResp),
        }).then();
        if (verificationResp.status === 200) {
            window.location.replace(params.next_url);
        } else {
            elemError.innerText = 'Signature verification failed! Status: ' + verificationResp.status;
        }
    });

});
