added more users and anonymous API

reduced time window to 3 seconds
This commit is contained in:
Walter Oggioni
2024-02-14 13:29:57 +08:00
parent 68c41b9b95
commit 852c3e82fc
2 changed files with 73 additions and 18 deletions

View File

@@ -67,6 +67,11 @@ loginButton.addEventListener('click', async evt => {
},
body: JSON.stringify({ username: loginForm.username.value, password: loginForm.password.value})
}).then(async response => {
if (!response.ok) {
let paragraph = document.createElement('p');
paragraph.textContent = await response.text();
document.body.appendChild(paragraph);
}
const nonceHeader = response.headers.get('nonce');
const encryptedNonce = atob(nonceHeader);
const privateKey = (await keyPair).privateKey;
@@ -74,26 +79,55 @@ loginButton.addEventListener('click', async evt => {
const encryptedBuffer = Uint8Array.from(atob(nonceHeader), c => c.charCodeAt(0));
nonce = await crypto.decrypt({ name: "RSA-OAEP" }, privateKey, encryptedBuffer)
.then(it => new Uint8Array(it));
return response.text();
}).then(text => {
});
});
async function computeToken() {
if(nonce != null) {
const crypto = window.crypto.subtle;
const epochTick = Math.floor(new Date().getTime() / 3000);
const data = concatenateUInt8Arrays(nonce, integerToBytes(epochTick, 8));
const hash = new Uint8Array(await crypto.digest("SHA-256", data));
const token = btoa(Array.from(hash, byte => String.fromCharCode(byte)).join(''));
return token;
} else {
return null;
}
}
let div = document.createElement('div');
document.body.appendChild(div);
let whoamiButton = document.createElement('button');
whoamiButton.textContent = 'whoami'
div.appendChild(whoamiButton);
whoamiButton.addEventListener('click', async evt => {
const token = await computeToken();
let headers = {};
if (token != null) {
headers = {
'x-token': token
};
}
fetch('api/whoami', {
method: 'GET',
headers
}).then(response => response.text()).then(text => {
let paragraph = document.createElement('p');
paragraph.textContent = text;
document.body.appendChild(paragraph);
});
});
let button = document.createElement('button');
button.textContent = 'Press me'
document.body.appendChild(button);
let helloButton = document.createElement('button');
helloButton.textContent = 'hello'
div.appendChild(helloButton);
button.addEventListener('click', async evt => {
let header = {};
if(nonce != null) {
const crypto = window.crypto.subtle;
const epochTick = Math.floor(new Date().getTime() / 10000)
const data = concatenateUInt8Arrays(nonce, integerToBytes(epochTick, 8))
const hash = new Uint8Array(await crypto.digest("SHA-256", data));
const token = btoa(Array.from(hash, byte => String.fromCharCode(byte)).join(''));
helloButton.addEventListener('click', async evt => {
const token = await computeToken();
let headers = {};
if (token != null) {
headers = {
'x-token': token
};