{% extends "multifactor/FIDO2/add.html" %}{% load static %}

{% block fido_scripting %}
<script type="module">
import {
	get,
	parseRequestOptionsFromJSON,
} from '{% static 'multifactor/js/webauthn-json.browser-ponyfill.js'%}'

function authenticate() {
	fetch("{% url 'multifactor:fido2_begin_auth' %}", {method: 'POST'})
	.then((response) => {
		if(response.ok)
			return response.json()
		throw new Error('No credential available to authenticate!')
	})
	.then((json) => {
		const options = parseRequestOptionsFromJSON(json)
		return get(options)
	})
	.then((attest) => {
		return fetch("{% url 'multifactor:fido2_complete_auth' %}", {
			method: 'POST',
			body: JSON.stringify(attest),
		})
		.then((response) => {
			if (response.ok)
				return response.json()
		})
		.then((res) => {
			if (res.status=="OK") {
				window.location.href = res.redirect
			}
			else {
				display_error("Error occured, please reload to try again.")
			}
		})
	}, (error)  =>{
		var el = document.getElementById('authtype')
		el.classList.add('manual')
		el.classList.remove('automatic')
	})
}
window.authenticate = authenticate

setTimeout(authenticate, 300);
</script>
{% endblock fido_scripting %}