V.1.2 - Improved Secrurity, Better Ticket Handling
This commit is contained in:
1 parent
cb5d091be2
commit
3136c81533
16 files changed
+879
-738
No files matched your search
+83
-189
@@ -1,121 +1,82 @@
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
const isAdminView = document.body.classList.contains('admin-view');
|
||||
const createForm = document.getElementById('create-form');
|
||||
const ticketsContainer = document.getElementById('tickets-container');
|
||||
|
||||
const statusFilter = document.getElementById('status-filter');
|
||||
const categoryFilter = document.getElementById('category-filter');
|
||||
const searchInput = document.getElementById('search-input');
|
||||
|
||||
// Webhook configuration - will be loaded dynamically
|
||||
let webhookConfig = null;
|
||||
|
||||
// --- Ticket Modal Elements ---
|
||||
const openModalBtn = document.getElementById('open-modal-btn');
|
||||
const modal = document.getElementById('create-ticket-modal');
|
||||
const closeModalBtn = document.getElementById('close-modal-btn');
|
||||
|
||||
// --- PFP Modal Elements ---
|
||||
const updatePfpBtn = document.getElementById('update-pfp-btn');
|
||||
const pfpModal = document.getElementById('update-pfp-modal');
|
||||
const closePfpModalBtn = document.getElementById('close-pfp-modal-btn');
|
||||
const dropZone = document.getElementById('drop-zone');
|
||||
const fileInput = document.getElementById('pfp-file-input');
|
||||
const uploadPfpBtn = document.getElementById('upload-pfp-btn');
|
||||
|
||||
// Accordion elements
|
||||
const closedToggle = document.getElementById('closed-toggle');
|
||||
const closedAccordion = document.getElementById('closed-accordion');
|
||||
const closedCount = document.getElementById('closed-count');
|
||||
|
||||
let selectedPfpFile = null;
|
||||
let allTickets = [];
|
||||
let accordionOpen = false;
|
||||
|
||||
// --- XSS Protection ---
|
||||
function escapeHtml(str) {
|
||||
if (!str) return '';
|
||||
const div = document.createElement('div');
|
||||
div.textContent = str;
|
||||
return div.innerHTML;
|
||||
}
|
||||
|
||||
// --- Helper ---
|
||||
function formatStatusClass(status) {
|
||||
if (!status) return 'Unknown';
|
||||
return status
|
||||
.split(' ')
|
||||
.map(s => s.charAt(0).toUpperCase() + s.slice(1).toLowerCase())
|
||||
.join('-');
|
||||
return status.split(' ').map(s => s.charAt(0).toUpperCase() + s.slice(1).toLowerCase()).join('-');
|
||||
}
|
||||
|
||||
// --- Webhook Functions ---
|
||||
async function loadWebhookConfig() {
|
||||
// --- Dynamic Categories ---
|
||||
async function loadCategories() {
|
||||
try {
|
||||
const response = await fetch('/api/webhooks');
|
||||
if (response.ok) {
|
||||
webhookConfig = await response.json();
|
||||
console.log('Webhook configuration loaded:', webhookConfig.configured);
|
||||
} else {
|
||||
console.warn('Failed to load webhook configuration');
|
||||
webhookConfig = { admin: null, user: null, configured: { admin: false, user: false } };
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error loading webhook configuration:', error);
|
||||
webhookConfig = { admin: null, user: null, configured: { admin: false, user: false } };
|
||||
const res = await fetch('/api/categories');
|
||||
const categories = await res.json();
|
||||
populateCategorySelects(categories);
|
||||
} catch (err) {
|
||||
console.error('Failed to load categories:', err);
|
||||
}
|
||||
}
|
||||
|
||||
async function sendWebhookNotification(webhookUrl, message) {
|
||||
if (!webhookUrl) {
|
||||
console.log('No webhook URL provided, skipping notification');
|
||||
return;
|
||||
function populateCategorySelects(categories) {
|
||||
// Modal create form select
|
||||
const createSelect = document.getElementById('category');
|
||||
if (createSelect) {
|
||||
createSelect.innerHTML = categories.map(c => `<option value="${escapeHtml(c)}">${escapeHtml(c)}</option>`).join('');
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(webhookUrl, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(message)
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
console.error(`Webhook notification failed: ${response.status} ${response.statusText}`);
|
||||
} else {
|
||||
console.log('Webhook notification sent successfully');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to send webhook notification:', error);
|
||||
// Filter select (keep "All Categories" as first option)
|
||||
if (categoryFilter) {
|
||||
categoryFilter.innerHTML = '<option value="all">All Categories</option>' +
|
||||
categories.map(c => `<option value="${escapeHtml(c)}">${escapeHtml(c)}</option>`).join('');
|
||||
}
|
||||
}
|
||||
|
||||
async function sendAdminWebhook(ticket) {
|
||||
if (!webhookConfig?.admin) {
|
||||
console.log('Admin webhook not configured, skipping notification');
|
||||
return;
|
||||
}
|
||||
|
||||
const message = {
|
||||
embeds: [{
|
||||
title: '🎫 New Ticket Created',
|
||||
description: `**Ticket #${ticket.id}**: ${ticket.title}`,
|
||||
fields: [
|
||||
{ name: '👤 Requester', value: 'Laila' },
|
||||
{ name: '📊 Status', value: ticket.status || 'Open', inline: true },
|
||||
{ name: '⚡ Priority', value: ticket.priority || 'None', inline: true },
|
||||
{ name: '📂 Category', value: ticket.category || 'None', inline: true },
|
||||
{ name: '📝 Description', value: ticket.description.length > 100 ?
|
||||
ticket.description.substring(0, 100) + '...' :
|
||||
ticket.description, inline: false }
|
||||
],
|
||||
timestamp: new Date().toISOString(),
|
||||
color: 0x00ff00,
|
||||
footer: {
|
||||
text: 'Ticket System',
|
||||
icon_url: 'https://cdn-icons-png.flaticon.com/512/2666/2666505.png'
|
||||
}
|
||||
}]
|
||||
};
|
||||
|
||||
await sendWebhookNotification(webhookConfig.admin, message);
|
||||
// --- Accordion ---
|
||||
if (closedToggle) {
|
||||
closedToggle.addEventListener('click', () => {
|
||||
accordionOpen = !accordionOpen;
|
||||
closedAccordion.style.display = accordionOpen ? 'block' : 'none';
|
||||
closedToggle.classList.toggle('open', accordionOpen);
|
||||
});
|
||||
}
|
||||
|
||||
// --- Ticket Modal Open/Close ---
|
||||
// --- Ticket Modal ---
|
||||
function openModal() {
|
||||
if (modal) {
|
||||
const scrollBarWidth = window.innerWidth - document.documentElement.clientWidth;
|
||||
modal.style.display = 'flex';
|
||||
document.body.style.overflow = 'hidden';
|
||||
document.documentElement.style.overflow = 'hidden';
|
||||
if (scrollBarWidth > 0) {
|
||||
document.body.style.paddingRight = scrollBarWidth + 'px';
|
||||
}
|
||||
if (scrollBarWidth > 0) document.body.style.paddingRight = scrollBarWidth + 'px';
|
||||
}
|
||||
}
|
||||
function closeModal() {
|
||||
@@ -126,31 +87,21 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
document.body.style.paddingRight = '';
|
||||
}
|
||||
}
|
||||
function outsideClickListener(event) {
|
||||
if (event.target === modal) closeModal();
|
||||
}
|
||||
function escKeyListener(event) {
|
||||
if (event.key === 'Escape' && modal.style.display === 'flex') {
|
||||
closeModal();
|
||||
}
|
||||
}
|
||||
if (openModalBtn) openModalBtn.addEventListener('click', openModal);
|
||||
if (closeModalBtn) closeModalBtn.addEventListener('click', closeModal);
|
||||
if (modal) {
|
||||
window.addEventListener('click', outsideClickListener);
|
||||
window.addEventListener('keydown', escKeyListener);
|
||||
window.addEventListener('click', (e) => { if (e.target === modal) closeModal(); });
|
||||
window.addEventListener('keydown', (e) => { if (e.key === 'Escape' && modal.style.display === 'flex') closeModal(); });
|
||||
}
|
||||
|
||||
// --- PFP Modal Open/Close ---
|
||||
// --- PFP Modal ---
|
||||
function openPfpModal() {
|
||||
if (pfpModal) {
|
||||
const scrollBarWidth = window.innerWidth - document.documentElement.clientWidth;
|
||||
pfpModal.style.display = 'flex';
|
||||
document.body.style.overflow = 'hidden';
|
||||
document.documentElement.style.overflow = 'hidden';
|
||||
if (scrollBarWidth > 0) {
|
||||
document.body.style.paddingRight = scrollBarWidth + 'px';
|
||||
}
|
||||
if (scrollBarWidth > 0) document.body.style.paddingRight = scrollBarWidth + 'px';
|
||||
}
|
||||
}
|
||||
function closePfpModal() {
|
||||
@@ -162,26 +113,16 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
}
|
||||
}
|
||||
if (updatePfpBtn) updatePfpBtn.addEventListener('click', openPfpModal);
|
||||
if (closePfpModalBtn) closePfpModalBtn.addEventListener('click', closePfpModal);
|
||||
if (pfpModal) {
|
||||
window.addEventListener('click', (e) => {
|
||||
if (e.target === pfpModal) closePfpModal();
|
||||
});
|
||||
window.addEventListener('keydown', (e) => {
|
||||
if (e.key === 'Escape' && pfpModal.style.display === 'flex') closePfpModal();
|
||||
});
|
||||
window.addEventListener('click', (e) => { if (e.target === pfpModal) closePfpModal(); });
|
||||
window.addEventListener('keydown', (e) => { if (e.key === 'Escape' && pfpModal.style.display === 'flex') closePfpModal(); });
|
||||
}
|
||||
|
||||
// --- Drag & Drop Logic ---
|
||||
// --- Drag & Drop ---
|
||||
if (dropZone) {
|
||||
dropZone.addEventListener('click', () => fileInput.click());
|
||||
dropZone.addEventListener('dragover', (e) => {
|
||||
e.preventDefault();
|
||||
dropZone.style.borderColor = '#10b981';
|
||||
});
|
||||
dropZone.addEventListener('dragleave', () => {
|
||||
dropZone.style.borderColor = '#4b5563';
|
||||
});
|
||||
dropZone.addEventListener('dragover', (e) => { e.preventDefault(); dropZone.style.borderColor = '#10b981'; });
|
||||
dropZone.addEventListener('dragleave', () => { dropZone.style.borderColor = '#4b5563'; });
|
||||
dropZone.addEventListener('drop', (e) => {
|
||||
e.preventDefault();
|
||||
dropZone.style.borderColor = '#4b5563';
|
||||
@@ -192,7 +133,6 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (fileInput) {
|
||||
fileInput.addEventListener('change', (e) => {
|
||||
const file = e.target.files[0];
|
||||
@@ -202,21 +142,13 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// --- Upload PFP ---
|
||||
if (uploadPfpBtn) {
|
||||
uploadPfpBtn.addEventListener('click', async () => {
|
||||
if (!selectedPfpFile) {
|
||||
alert('Please select an image first.');
|
||||
return;
|
||||
}
|
||||
if (!selectedPfpFile) return alert('Please select an image first.');
|
||||
const formData = new FormData();
|
||||
formData.append('pfp', selectedPfpFile, 'user.jpg');
|
||||
try {
|
||||
const res = await fetch('/api/upload-pfp', {
|
||||
method: 'POST',
|
||||
body: formData
|
||||
});
|
||||
const res = await fetch('/api/upload-pfp', { method: 'POST', body: formData });
|
||||
if (!res.ok) throw new Error('Upload failed');
|
||||
alert('Profile picture updated!');
|
||||
closePfpModal();
|
||||
@@ -239,23 +171,18 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
}
|
||||
}
|
||||
async function createTicket(ticket) {
|
||||
try {
|
||||
const res = await fetch('/api/tickets', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(ticket)
|
||||
});
|
||||
return await res.json();
|
||||
} catch (err) {
|
||||
console.error('Error creating ticket:', err);
|
||||
throw err;
|
||||
}
|
||||
const res = await fetch('/api/tickets', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(ticket),
|
||||
});
|
||||
if (!res.ok) throw new Error('Failed to create ticket');
|
||||
return await res.json();
|
||||
}
|
||||
|
||||
// --- Date Formatting ---
|
||||
function formatDate(dateStr) {
|
||||
return new Date(dateStr).toLocaleDateString(undefined, {
|
||||
year: 'numeric', month: 'short', day: 'numeric'
|
||||
year: 'numeric', month: 'short', day: 'numeric',
|
||||
});
|
||||
}
|
||||
|
||||
@@ -265,38 +192,19 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
const category = categoryFilter?.value || 'all';
|
||||
const search = searchInput?.value.trim().toLowerCase() || '';
|
||||
|
||||
const openTickets = allTickets.filter(ticket =>
|
||||
(ticket.status || '').toLowerCase() !== 'closed'
|
||||
);
|
||||
const closedTickets = allTickets.filter(ticket =>
|
||||
(ticket.status || '').toLowerCase() === 'closed'
|
||||
);
|
||||
|
||||
const filteredOpen = openTickets.filter(ticket => {
|
||||
const filtered = allTickets.filter(ticket => {
|
||||
const ticketStatus = (ticket.status || '').toLowerCase();
|
||||
const ticketCategory = (ticket.category || '').toLowerCase();
|
||||
const ticketTitle = (ticket.title || '').toLowerCase();
|
||||
const ticketDescription = (ticket.description || '').toLowerCase();
|
||||
const isClosed = ticketStatus === 'closed';
|
||||
const matchesStatus = status === 'all' || ticketStatus === status.toLowerCase();
|
||||
const matchesCategory = category === 'all' || ticketCategory === category.toLowerCase();
|
||||
const matchesSearch =
|
||||
ticketTitle.includes(search) ||
|
||||
ticketDescription.includes(search);
|
||||
return matchesStatus && matchesCategory && matchesSearch;
|
||||
const matchesSearch = ticketTitle.includes(search) || ticketDescription.includes(search);
|
||||
return (isClosed || matchesStatus) && matchesCategory && matchesSearch;
|
||||
});
|
||||
|
||||
const filteredClosed = closedTickets.filter(ticket => {
|
||||
const ticketCategory = (ticket.category || '').toLowerCase();
|
||||
const ticketTitle = (ticket.title || '').toLowerCase();
|
||||
const ticketDescription = (ticket.description || '').toLowerCase();
|
||||
const matchesCategory = category === 'all' || ticketCategory === category.toLowerCase();
|
||||
const matchesSearch =
|
||||
ticketTitle.includes(search) ||
|
||||
ticketDescription.includes(search);
|
||||
return matchesCategory && matchesSearch;
|
||||
});
|
||||
|
||||
renderTickets([...filteredOpen, ...filteredClosed]);
|
||||
renderTickets(filtered);
|
||||
}
|
||||
|
||||
function renderTickets(tickets) {
|
||||
@@ -304,6 +212,9 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
const closedContainer = document.getElementById('closed-tickets-container');
|
||||
openContainer.innerHTML = '';
|
||||
closedContainer.innerHTML = '';
|
||||
|
||||
let closedTicketCount = 0;
|
||||
|
||||
if (!tickets.length) {
|
||||
openContainer.innerHTML = `
|
||||
<div class="empty-state">
|
||||
@@ -311,29 +222,31 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
<h3>No tickets found</h3>
|
||||
<p>Try changing your filters or create a new ticket</p>
|
||||
</div>`;
|
||||
closedContainer.innerHTML = '';
|
||||
if (closedCount) closedCount.textContent = '0';
|
||||
return;
|
||||
}
|
||||
|
||||
tickets.sort((a, b) => new Date(b.created_at) - new Date(a.created_at));
|
||||
|
||||
tickets.forEach(ticket => {
|
||||
const statusSafe = formatStatusClass(ticket.status);
|
||||
const prioritySafe = (ticket.priority || 'None');
|
||||
const prioritySafe = ticket.priority || 'None';
|
||||
const el = document.createElement('div');
|
||||
el.className = `ticket status-${statusSafe.replace(/\s+/g, '-')}`;
|
||||
el.innerHTML = `
|
||||
<h3>${ticket.title} <span class="ticket-id">#${ticket.id}</span> <small class="total-time"> Time Cin: (${ticket.total_time} min)</small> </h3>
|
||||
<p class="description">${ticket.description}</p>
|
||||
<h3>${escapeHtml(ticket.title)} <span class="ticket-id">#${ticket.id}</span> <small class="total-time">Time: (${ticket.total_time} min)</small></h3>
|
||||
<p class="description">${escapeHtml(ticket.description)}</p>
|
||||
<div class="meta">
|
||||
<span class="requester"><i class="fas fa-user"></i> ${ticket.requester}</span>
|
||||
<span class="requester"><i class="fas fa-user"></i> ${escapeHtml(ticket.requester)}</span>
|
||||
<span class="date"><i class="fas fa-calendar"></i> ${formatDate(ticket.created_at)}</span>
|
||||
${ticket.category ? `<span class="category"><i class="fas fa-tag"></i> ${ticket.category}</span>` : ''}
|
||||
${ticket.category ? `<span class="category"><i class="fas fa-tag"></i> ${escapeHtml(ticket.category)}</span>` : ''}
|
||||
</div>
|
||||
<div class="status-row">
|
||||
<div class="status status-${statusSafe.replace(/\s+/g, '-')}">
|
||||
<i class="fas fa-circle"></i> ${ticket.status}
|
||||
<i class="fas fa-circle"></i> ${escapeHtml(ticket.status)}
|
||||
</div>
|
||||
<div class="priority priority-${prioritySafe.replace(/\s+/g, '-')}">
|
||||
<i class="fas fa-flag"></i> ${prioritySafe}
|
||||
<i class="fas fa-flag"></i> ${escapeHtml(prioritySafe)}
|
||||
</div>
|
||||
</div>
|
||||
<div class="ticket-actions">
|
||||
@@ -344,14 +257,17 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
`;
|
||||
if ((ticket.status || '').toLowerCase() === 'closed') {
|
||||
closedContainer.appendChild(el);
|
||||
closedTicketCount++;
|
||||
} else {
|
||||
openContainer.appendChild(el);
|
||||
}
|
||||
});
|
||||
|
||||
if (closedCount) closedCount.textContent = closedTicketCount;
|
||||
}
|
||||
|
||||
// --- Handlers ---
|
||||
let isSubmittingTicket = false; // prevent double submit
|
||||
let isSubmittingTicket = false;
|
||||
|
||||
async function handleCreateTicket(e) {
|
||||
e.preventDefault();
|
||||
@@ -372,28 +288,11 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
const submitBtn = createForm.querySelector('.btn-primary');
|
||||
submitBtn.disabled = true;
|
||||
|
||||
const ticket = {
|
||||
title,
|
||||
description,
|
||||
priority,
|
||||
category,
|
||||
requester: 'Laila',
|
||||
status: 'Open'
|
||||
};
|
||||
|
||||
try {
|
||||
const createdTicket = await createTicket(ticket);
|
||||
await createTicket({ title, description, priority, category, requester: 'Laila', status: 'Open' });
|
||||
createForm.reset();
|
||||
closeModal();
|
||||
await refreshTickets();
|
||||
await sendAdminWebhook({
|
||||
id: createdTicket.id,
|
||||
title,
|
||||
description,
|
||||
priority,
|
||||
category,
|
||||
status: 'Open'
|
||||
});
|
||||
|
||||
submitBtn.innerHTML = '<i class="fas fa-check"></i> Created!';
|
||||
submitBtn.style.backgroundColor = '#28a745';
|
||||
@@ -416,15 +315,10 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
}
|
||||
|
||||
// --- Init ---
|
||||
async function initialize() {
|
||||
await loadWebhookConfig();
|
||||
await refreshTickets();
|
||||
}
|
||||
|
||||
if (createForm) createForm.addEventListener('submit', handleCreateTicket);
|
||||
if (statusFilter) statusFilter.addEventListener('change', renderFilteredTickets);
|
||||
if (categoryFilter) categoryFilter.addEventListener('change', renderFilteredTickets);
|
||||
if (searchInput) searchInput.addEventListener('input', renderFilteredTickets);
|
||||
|
||||
initialize();
|
||||
loadCategories().then(() => refreshTickets());
|
||||
});
|
||||
Reference in new issue
Block a user