75 lines
2.3 KiB
JavaScript
75 lines
2.3 KiB
JavaScript
async function submitAuthForm(endpoint, email, password, errorElement) {
|
|
errorElement.hidden = true;
|
|
errorElement.textContent = '';
|
|
|
|
const response = await fetch(endpoint, {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
credentials: 'same-origin',
|
|
body: JSON.stringify({ email, password }),
|
|
});
|
|
|
|
if (response.ok) {
|
|
window.location.href = '/home';
|
|
return;
|
|
}
|
|
|
|
let message = 'Something went wrong';
|
|
try {
|
|
const body = await response.json();
|
|
if (body.error) {
|
|
message = body.error;
|
|
}
|
|
} catch (parseError) {
|
|
// fall through to generic message
|
|
}
|
|
errorElement.textContent = message;
|
|
errorElement.hidden = false;
|
|
}
|
|
|
|
async function logout() {
|
|
await fetch('/api/auth/logout', {
|
|
method: 'POST',
|
|
credentials: 'same-origin',
|
|
});
|
|
window.location.href = '/login';
|
|
}
|
|
|
|
document.addEventListener('DOMContentLoaded', () => {
|
|
const loginForm = document.getElementById('login-form');
|
|
if (loginForm !== null) {
|
|
const errorElement = document.getElementById('login-error');
|
|
loginForm.addEventListener('submit', async (submitEvent) => {
|
|
submitEvent.preventDefault();
|
|
const email = document.getElementById('email').value;
|
|
const password = document.getElementById('password').value;
|
|
await submitAuthForm(
|
|
'/api/auth/login',
|
|
email,
|
|
password,
|
|
errorElement,
|
|
);
|
|
});
|
|
}
|
|
|
|
const registerForm = document.getElementById('register-form');
|
|
if (registerForm !== null) {
|
|
const errorElement = document.getElementById('register-error');
|
|
registerForm.addEventListener('submit', async (submitEvent) => {
|
|
submitEvent.preventDefault();
|
|
const email = document.getElementById('email').value;
|
|
const password = document.getElementById('password').value;
|
|
await submitAuthForm(
|
|
'/api/auth/register',
|
|
email,
|
|
password,
|
|
errorElement,
|
|
);
|
|
});
|
|
}
|
|
|
|
const logoutButton = document.getElementById('logout');
|
|
if (logoutButton !== null) {
|
|
logoutButton.addEventListener('click', logout);
|
|
}
|
|
});
|