Anjay / public /admin.js
maylinejix's picture
Upload 7 files
50c1c55 verified
// admin.js - Admin Panel JavaScript
const loginSection = document.getElementById('login-section');
const createSection = document.getElementById('create-section');
const loginForm = document.getElementById('login-form');
const createForm = document.getElementById('create-form');
// Check if already logged in
if (localStorage.getItem('admin_token')) {
loginSection.style.display = 'none';
createSection.style.display = 'block';
}
loginForm.addEventListener('submit', async (e) => {
e.preventDefault();
const password = document.getElementById('password').value;
try {
const response = await fetch('/api/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ password })
});
const data = await response.json();
if (data.success) {
localStorage.setItem('admin_token', data.token);
loginSection.style.display = 'none';
createSection.style.display = 'block';
showAlert('success', 'Login successful!');
} else {
showAlert('error', 'Invalid password');
}
} catch (error) {
showAlert('error', 'Login failed');
}
});
createForm.addEventListener('submit', async (e) => {
e.preventDefault();
const title = document.getElementById('title').value;
const redirect = document.getElementById('redirect').value;
const name = document.getElementById('name').value;
const verify = document.getElementById('verify').checked;
const token = localStorage.getItem('admin_token');
try {
const response = await fetch('/api/create', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
},
body: JSON.stringify({ title, redirect, name, verify })
});
const data = await response.json();
if (data.success) {
showAlert('success', 'Short link created successfully!');
createForm.reset();
setTimeout(() => {
window.location.href = '/home';
}, 2000);
} else {
showAlert('error', 'Failed to create link');
}
} catch (error) {
showAlert('error', 'Failed to create link');
}
});
function logout() {
localStorage.removeItem('admin_token');
window.location.href = '/home';
}
function showAlert(type, message) {
const container = document.getElementById('alert-container');
const alert = document.createElement('div');
alert.className = `alert alert-${type}`;
let icon = 'fa-check-circle';
if (type === 'error') icon = 'fa-exclamation-circle';
else if (type === 'info') icon = 'fa-info-circle';
alert.innerHTML = `
<span class="alert-icon"><i class="fas ${icon}"></i></span>
<span>${message}</span>
<button class="alert-close" onclick="this.parentElement.remove()">
<i class="fas fa-times"></i>
</button>
`;
container.appendChild(alert);
setTimeout(() => alert.remove(), 5000);
}