Initial commit: Retribusi frontend dengan dashboard, event logs, dan settings
This commit is contained in:
86
public/dashboard/js/auth.js
Normal file
86
public/dashboard/js/auth.js
Normal file
@@ -0,0 +1,86 @@
|
||||
// public/dashboard/js/auth.js
|
||||
// Handles login flow and auth helpers (JWT in localStorage)
|
||||
|
||||
import { apiLogin } from './api.js';
|
||||
|
||||
const TOKEN_KEY = 'token';
|
||||
const USER_KEY = 'user';
|
||||
|
||||
export const Auth = {
|
||||
isAuthenticated() {
|
||||
return !!localStorage.getItem(TOKEN_KEY);
|
||||
},
|
||||
|
||||
saveToken(token) {
|
||||
localStorage.setItem(TOKEN_KEY, token);
|
||||
},
|
||||
|
||||
saveUser(user) {
|
||||
localStorage.setItem(USER_KEY, JSON.stringify(user || {}));
|
||||
},
|
||||
|
||||
logout() {
|
||||
localStorage.removeItem(TOKEN_KEY);
|
||||
localStorage.removeItem(USER_KEY);
|
||||
window.location.href = '../index.php';
|
||||
}
|
||||
};
|
||||
|
||||
async function handleLoginSubmit(event) {
|
||||
event.preventDefault();
|
||||
|
||||
const form = event.currentTarget;
|
||||
const usernameInput = form.querySelector('#username');
|
||||
const passwordInput = form.querySelector('#password');
|
||||
const errorBox = document.getElementById('login-error');
|
||||
const submitBtn = form.querySelector('button[type="submit"]');
|
||||
|
||||
if (errorBox) {
|
||||
errorBox.classList.remove('visible');
|
||||
errorBox.textContent = '';
|
||||
}
|
||||
|
||||
submitBtn.disabled = true;
|
||||
submitBtn.textContent = 'Masuk...';
|
||||
|
||||
try {
|
||||
const username = usernameInput.value.trim();
|
||||
const password = passwordInput.value;
|
||||
|
||||
const data = await apiLogin(username, password);
|
||||
const token = data.token;
|
||||
const user = data.user;
|
||||
|
||||
if (!token) {
|
||||
throw new Error('Token tidak ditemukan dalam response login.');
|
||||
}
|
||||
|
||||
Auth.saveToken(token);
|
||||
Auth.saveUser(user);
|
||||
|
||||
window.location.href = 'dashboard.html';
|
||||
} catch (err) {
|
||||
console.error('Login failed', err);
|
||||
if (errorBox) {
|
||||
errorBox.textContent = err.message || 'Login gagal. Silakan coba lagi.';
|
||||
errorBox.classList.add('visible');
|
||||
}
|
||||
} finally {
|
||||
submitBtn.disabled = false;
|
||||
submitBtn.textContent = 'Login';
|
||||
}
|
||||
}
|
||||
|
||||
// Attach events on login page only
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
const form = document.getElementById('login-form');
|
||||
if (form) {
|
||||
if (Auth.isAuthenticated()) {
|
||||
window.location.href = 'dashboard.html';
|
||||
return;
|
||||
}
|
||||
form.addEventListener('submit', handleLoginSubmit);
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
Reference in New Issue
Block a user