Files
vintagecoding.net/js/login.js
T
2025-05-01 14:42:12 -06:00

73 lines
2.3 KiB
JavaScript

const form = document.querySelector('#login_form');
const username_field = form.querySelector('#username');
const password_field = form.querySelector('#password');
const password_hash_field = form.querySelector('#password_hash');
const submit_button = form.querySelector('input[type="submit"]');
submit_button.addEventListener('click', async (e) => {
e.preventDefault();
const password_hash = await hashString(password_field.value);
const urlParams = new URLSearchParams(document.location.search);
const redirect = decodeURI(urlParams.get('redirect'));
requestAuth(username_field.value, password_hash, redirect);
});
function requestAuth(username, password_hash, redirect) {
fetch('http://localhost:7477/auth', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: 'username=' + username + '&password_hash=' + password_hash,
})
.then(response => {
if (!response.ok) {
console.log('Login Failed!');
}
return response.json(); // Parse response body as JSON
})
.then(data => {
notifyServer(data["id"], username, 1, redirect);
});
}
function notifyServer(id, username, role, redirect) {
fetch('director.php', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: 'ajax_id=login&user_id=' + id + '&username=' + username + '&role=' + role,
})
.then(response => {
return response.json();
})
.then(data => {
if ('startViewTransition' in document) {
document.startViewTransition(() => {
if (redirect == null) {
window.location.href = 'articles.php?view=list&sort=new';
} else {
window.location.href = redirect;
}
});
} else {
// Fallback for browsers that don't support View Transitions
if (redirect == null) {
window.location.href = 'articles.php?view=list&sort=new';
} else {
window.location.href = redirect;
}
}
});
}
async function hashString(str) {
const encoded = new TextEncoder().encode(str);
const digest = await crypto.subtle.digest('SHA-256', encoded);
const hashArray = Array.from(new Uint8Array(digest));
const hashHex = hashArray.map(byte => byte.toString(16).padStart(2, '0')).join('');
return hashHex;
}