add auth javascript
This commit is contained in:
parent
ce029fafa2
commit
cb697daa03
1 changed files with 75 additions and 0 deletions
75
public/js/auth.js
Normal file
75
public/js/auth.js
Normal file
|
|
@ -0,0 +1,75 @@
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
});
|
||||||
Loading…
Add table
Add a link
Reference in a new issue