puerta/internal/server/static/index.js

66 lines
1.4 KiB
JavaScript
Raw Normal View History

2023-01-04 04:21:49 +00:00
// SPDX-License-Identifier: Apache-2.0
// Copyright © 2022 Roberto Hidalgo <nidito@un.rob.mx>
2022-12-30 06:51:51 +00:00
const button = document.querySelector("#open button")
const form = document.querySelector("#open")
2023-01-03 07:40:38 +00:00
import * as webauthn from "./webauthn.js"
2022-12-30 06:51:51 +00:00
2023-01-04 04:21:49 +00:00
const host = document.location.protocol + "//" + document.location.host
// const host = "http://localhost:8081"
2023-01-03 07:40:38 +00:00
async function RequestToEnter() {
2022-12-30 06:51:51 +00:00
console.debug("requesting to enter")
2023-01-03 07:40:38 +00:00
let response = await webauthn.withAuth(`${host}/api/rex`, {
2022-12-30 06:51:51 +00:00
method: 'POST',
2023-01-03 07:40:38 +00:00
credentials: "include"
2022-12-30 06:51:51 +00:00
})
if (!response.ok) {
let message = response.statusText
try {
let json = await response.json()
if (json.message) {
message = `${message}: ${json.message}`
}
} catch {}
throw new Error(message);
}
let json = {}
try {
json = await response.json()
} catch {}
2023-01-03 07:40:38 +00:00
if (json.status == "ok") {
2022-12-30 06:51:51 +00:00
console.debug("Door opened")
}
return response.status
}
function clearStatus() {
form.classList.remove("failed")
form.classList.remove("success")
}
button.addEventListener("click", function(evt){
evt.preventDefault()
button.disabled = true
clearStatus()
RequestToEnter().then(() => {
form.classList.add("success")
}).catch((err) => {
form.classList.add("failed")
console.error(`Error: ${err}`)
}).finally(() => {
form.classList.remove("requested")
button.disabled = false
setTimeout(clearStatus, 5000)
})
return false
})