blob: b835cb9322d024625e903b0eb55b02ce425c2403 [file] [log] [blame]
Adrià Vilanova Martínez5af86512023-12-02 20:44:16 +01001/* (license-header)
2 * hores
3 * Copyright (c) 2023 Adrià Vilanova Martínez
4 *
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU Affero General Public License as
7 * published by the Free Software Foundation, either version 3 of the
8 * License, or (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU Affero General Public License for more details.
14 *
15 * You should have received a copy of the GNU Affero General Public
16 * License along with this program.
17 * If not, see http://www.gnu.org/licenses/.
18 */
Copybara botbe50d492023-11-30 00:16:42 +010019window.addEventListener("load", function() {
20 document.querySelector(".addsecuritykey").addEventListener("click", function() {
21 document.querySelector("#addsecuritykey").showModal();
22 /* Or dialog.show(); to show the dialog without a backdrop. */
23 });
24
25 document.getElementById("registersecuritykey").addEventListener("click", e => {
26 e.preventDefault();
27
28 if (document.getElementById("addsecuritykeyform").reportValidity()) {
29 fetch("ajax/addsecuritykey.php", {
30 method: "POST"
31 }).then(response => {
32 if (response.status !== 200) {
33 response.text(); // @TODO: Remove this. It is only used so the response is available in Chrome Dev Tools
34 throw new Error("HTTP status is not 200.");
35 }
36
37 return response.json();
38 }).then(response => {
39 recursiveBase64StrToArrayBuffer(response);
40 return response;
41 }).then(createCredentialArgs => {
42 return navigator.credentials.create(createCredentialArgs);
43 }).then(cred => {
44 return {
45 clientDataJSON: cred.response.clientDataJSON ? arrayBufferToBase64(cred.response.clientDataJSON) : null,
46 attestationObject: cred.response.attestationObject ? arrayBufferToBase64(cred.response.attestationObject) : null,
47 name: document.getElementById("name").value
48 };
49 }).then(JSON.stringify).then(AuthenticatorAttestationResponse => {
50 return window.fetch("ajax/addsecuritykey2.php", {
51 method: "POST",
52 body: AuthenticatorAttestationResponse,
53 });
54 }).then(response => {
55 if (response.status !== 200) {
56 response.text(); // @TODO: remove this. It is only used so the response is available in Chrome Dev Tools
57 throw new Error("HTTP status is not 200 (2).");
58 }
59
60 return response.json();
61 }).then(json => {
62 if (json.status == "ok") {
63 document.location = "securitykeys.php?msg=securitykeyadded";
64 }
65 }).catch(err => console.error("An unexpected error occurred.", err));
66 }
67 });
68});