initial commit
This commit is contained in:
56
frontend/js/auth.js
Normal file
56
frontend/js/auth.js
Normal file
@@ -0,0 +1,56 @@
|
||||
/* FluentGerman.ai — Auth page logic */
|
||||
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
// If already logged in, redirect
|
||||
const token = getToken();
|
||||
const user = getUser();
|
||||
if (token && user) {
|
||||
window.location.href = user.is_admin ? '/admin.html' : '/chat.html';
|
||||
return;
|
||||
}
|
||||
|
||||
const form = document.getElementById('login-form');
|
||||
const errorEl = document.getElementById('login-error');
|
||||
|
||||
form.addEventListener('submit', async (e) => {
|
||||
e.preventDefault();
|
||||
errorEl.classList.add('hidden');
|
||||
|
||||
const username = document.getElementById('username').value.trim();
|
||||
const password = document.getElementById('password').value;
|
||||
|
||||
if (!username || !password) {
|
||||
errorEl.textContent = 'Please fill in all fields.';
|
||||
errorEl.classList.remove('hidden');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch('/api/auth/login', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ username, password }),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const err = await response.json().catch(() => ({}));
|
||||
throw new Error(err.detail || 'Login failed');
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
setToken(data.access_token);
|
||||
|
||||
// Fetch user info
|
||||
const meResp = await fetch('/api/auth/me', {
|
||||
headers: { 'Authorization': `Bearer ${data.access_token}` },
|
||||
});
|
||||
const userData = await meResp.json();
|
||||
setUser(userData);
|
||||
|
||||
window.location.href = userData.is_admin ? '/admin.html' : '/chat.html';
|
||||
} catch (err) {
|
||||
errorEl.textContent = err.message;
|
||||
errorEl.classList.remove('hidden');
|
||||
}
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user