63 lines
2.8 KiB
JavaScript
63 lines
2.8 KiB
JavaScript
document.addEventListener('DOMContentLoaded', () => {
|
|
// Tab switching
|
|
document.querySelectorAll('.auth-tab').forEach(tab => {
|
|
tab.addEventListener('click', () => {
|
|
const target = tab.dataset.tab;
|
|
document.querySelectorAll('.auth-tab').forEach(t => t.classList.remove('active'));
|
|
tab.classList.add('active');
|
|
document.querySelectorAll('.auth-form').forEach(f => f.classList.remove('active'));
|
|
document.getElementById(`${target}-form`).classList.add('active');
|
|
});
|
|
});
|
|
// Login button
|
|
document.getElementById('login-submit').addEventListener('click', async () => {
|
|
const username = document.getElementById('login-username').value.trim();
|
|
const password = document.getElementById('login-password').value;
|
|
if (!username || !password) {
|
|
showToast('Please enter username and password', true);
|
|
return;
|
|
}
|
|
try {
|
|
const res = await fetch(`${API_BASE}/login`, {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ username, password }),
|
|
credentials: 'include'
|
|
});
|
|
const data = await res.json();
|
|
if (!res.ok) throw new Error(data.error || 'Login failed');
|
|
showToast(`Welcome, ${data.username}`);
|
|
window.location.href = 'map-page.html';
|
|
} catch (err) {
|
|
showToast(err.message, true);
|
|
}
|
|
});
|
|
// Register button
|
|
document.getElementById('register-submit').addEventListener('click', async () => {
|
|
const username = document.getElementById('register-username').value.trim();
|
|
const password = document.getElementById('register-password').value;
|
|
if (!username || !password) {
|
|
showToast('Please enter username and password', true);
|
|
return;
|
|
}
|
|
if (password.length < 4) {
|
|
showToast('Password must be at least 4 characters', true);
|
|
return;
|
|
}
|
|
try {
|
|
const res = await fetch(`${API_BASE}/register`, {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ username, password }),
|
|
credentials: 'include'
|
|
});
|
|
const data = await res.json();
|
|
if (!res.ok) throw new Error(data.error || 'Registration failed');
|
|
showToast(`Registered as ${data.username}. Logging in...`);
|
|
window.location.href = 'map-page.html';
|
|
} catch (err) {
|
|
showToast(err.message, true);
|
|
}
|
|
});
|
|
});
|