{% extends "security/base.html" %}
{% from "security/_macros.html" import render_field_with_errors, render_field %}

{% block head_scripts %}
  {{ super() }}
  <script src="{{ url_for('static', filename='js/webauthn.js') }}"
          xmlns="http://www.w3.org/1999/html"></script>
  <script src="{{ url_for('static', filename='js/base64.js') }}"></script>
{% endblock head_scripts %}

{% block content %}
  {% include "security/_messages.html" %}
  <h1>{{ _fsdomain("Please Re-Authenticate Using Your WebAuthn Security Key") }}</h1>
  {% if not credential_options %}
    <form action="{{ url_for_security("wan_verify") }}{% if 'next' in request.args %}?next={{ request.args.next|urlencode }}{% endif %}" method="POST"
          name="wan_verify_form">
        {{ wan_verify_form.hidden_tag() }}
        {{ render_field(wan_verify_form.submit) }}
    </form>
  {% else %}
    <form action="{{ url_for_security("wan_verify_response", token=wan_state) }}{% if 'next' in request.args %}?next={{ request.args.next|urlencode }}{% endif %}" method="POST"
          name="wan_signin_response_form" id="wan-signin-response-form">
      {{ wan_signin_response_form.hidden_tag() }}
      <div id="wan-errors"></div>
    </form>
      <script type="text/javascript">
        handleSignin('{{ credential_options|safe }}')
        .then((result) => {
          if (result.credential) {
            document.getElementById("credential").value = result.credential
            {# We auto-submit this form - there is a Submit button on the
               form we could use - but there really isn't any reason to force the
               user to click yet another button
             #}
            document.forms["wan-signin-response-form"].submit()
          } else {
            const error_element = document.getElementById("wan-errors")
            error_element.innerHTML = `<em>${result.error_msg}</em`
          }
        })
      </script>
  {% endif %}
{% endblock %}
