V.1.2 - Improved Secrurity, Better Ticket Handling

This commit is contained in:
Honey committed 2026-02-26 23:15:05 +01:00
1 parent cb5d091be2
commit 3136c81533
16 files changed
+879 -738

No files matched your search

+68 -142
View File
@@ -1,11 +1,11 @@
import {
fetchTicket, fetchComments, fetchHistory, createComment, logTime,
formatDateTime, formatMinutes, getHistoryIcon
formatDateTime, formatMinutes, getHistoryIcon, escapeHtml, linkify
} from './ticket-shared.js';
document.addEventListener('DOMContentLoaded', async () => {
const ticketId = new URLSearchParams(window.location.search).get('id');
if (!ticketId) return window.location.href = '../admin.html';
if (!ticketId) return (window.location.href = '../admin.html');
const statusSelect = document.getElementById('status-select');
const priorityInput = document.getElementById('priority-text');
@@ -19,55 +19,26 @@ document.addEventListener('DOMContentLoaded', async () => {
const totalTimeDisplay = document.getElementById('total-time');
const timeForm = document.getElementById('time-booking-form');
let webhookConfig = null;
// Fetch Webhook Configuration
async function loadWebhookConfig() {
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 } };
}
}
// Send Webhook Notification
async function sendWebhook(message) {
if (!webhookConfig?.user) {
console.log('User webhook not configured, skipping notification');
return;
}
try {
const res = await fetch(webhookConfig.user, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ content: message })
});
if (!res.ok) {
console.error('User webhook failed:', res.statusText);
}
} catch (err) {
console.error('Error sending user webhook:', err);
}
}
let originalStatus = '', originalPriority = '', originalTitle = '', originalDesc = '', originalCategory = '';
// Load categories dynamically
async function loadCategories() {
try {
const res = await fetch('/api/categories');
const categories = await res.json();
if (categorySelect) {
categorySelect.innerHTML = categories.map(c =>
`<option value="${escapeHtml(c)}">${escapeHtml(c)}</option>`
).join('');
}
} catch (err) {
console.error('Failed to load categories:', err);
}
}
async function loadPage() {
loadWebhookConfig().then(() => {
loadTicketDetails();
loadComments();
loadHistory();
});
await loadCategories();
await Promise.all([loadTicketDetails(), loadComments(), loadHistory()]);
}
async function loadTicketDetails() {
@@ -84,9 +55,7 @@ document.addEventListener('DOMContentLoaded', async () => {
document.getElementById('ticket-requester').textContent = ticket.requester;
document.getElementById('ticket-created').textContent = formatDateTime(ticket.created_at);
document.getElementById('ticket-updated').textContent = formatDateTime(ticket.updated_at);
const totalMins = typeof ticket.total_time === 'number' ? ticket.total_time : 0;
totalTimeDisplay.textContent = formatMinutes(totalMins);
totalTimeDisplay.textContent = formatMinutes(typeof ticket.total_time === 'number' ? ticket.total_time : 0);
statusSelect.className = 'form-control status-' + (ticket.status || '').toLowerCase().replace(/\s+/g, '-');
@@ -98,54 +67,28 @@ document.addEventListener('DOMContentLoaded', async () => {
}
async function updateTicket({ status, priority, title, description, category, actor = 'Admin' }) {
try {
const ticket = await fetchTicket(ticketId); // Fetch ticket to get the requester
const requester = ticket.requester || ''; // Ensure requester is included in the update request
try {
const ticket = await fetchTicket(ticketId);
const requester = ticket.requester || '';
const res = await fetch(`/api/tickets/${ticketId}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ status, priority, title, description, category, actor, requester }) // Add requester
});
const res = await fetch(`/api/tickets/${ticketId}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ status, priority, title, description, category, author: actor, requester }),
});
if (!res.ok) throw new Error('Failed to update');
if (!res.ok) throw new Error('Failed to update');
alert('Ticket updated successfully');
// Webhooks are handled server-side now — no need to send from here
alert('Ticket updated successfully');
if (status !== originalStatus) {
await sendWebhook(`Ticket #${ticketId} status changed from "${originalStatus}" to "${status}"`);
originalStatus = status;
titleText.textContent = title;
descText.textContent = description;
await loadPage();
} catch (err) {
console.error('Update failed:', err);
alert('Error updating ticket');
}
if (priority !== originalPriority) {
await sendWebhook(`Ticket #${ticketId} priority changed from "${originalPriority}" to "${priority}"`);
originalPriority = priority;
}
if (title !== originalTitle) {
await sendWebhook(`Ticket #${ticketId} title changed by ${actor}`);
originalTitle = title;
}
if (description !== originalDesc) {
await sendWebhook(`Ticket #${ticketId} description changed by ${actor}`);
originalDesc = description;
}
if (category !== originalCategory) {
await sendWebhook(`Ticket #${ticketId} category changed from "${originalCategory}" to "${category}"`);
originalCategory = category;
}
titleText.textContent = title;
descText.textContent = description;
await loadPage();
} catch (err) {
console.error('Update failed:', err);
alert('Error updating ticket');
}
}
document.getElementById('update-ticket-btn').addEventListener('click', async () => {
const isEditingTitle = titleInput.style.display === 'block';
@@ -153,14 +96,16 @@ document.addEventListener('DOMContentLoaded', async () => {
const newTitle = isEditingTitle ? titleInput.value.trim() : titleText.textContent;
const newDesc = isEditingDesc ? descInput.value.trim() : descText.textContent;
const newStatus = statusSelect.value;
const newPriority = priorityInput.value;
const newCategory = categorySelect.value;
const confirmed = confirm('Möchten Sie die Änderungen wirklich speichern?');
if (!confirmed) return;
if (!confirm('Save changes?')) return;
await updateTicket({ status: newStatus, priority: newPriority, title: newTitle, description: newDesc, category: newCategory });
await updateTicket({
status: statusSelect.value,
priority: priorityInput.value,
title: newTitle,
description: newDesc,
category: categorySelect.value,
});
titleInput.style.display = 'none';
titleText.style.display = 'block';
@@ -169,16 +114,14 @@ document.addEventListener('DOMContentLoaded', async () => {
});
document.getElementById('close-ticket-btn').addEventListener('click', async () => {
const confirmed = confirm('Möchtest du das Ticket wirklich schließen?');
if (!confirmed) return;
const newStatus = 'Closed';
const newPriority = priorityInput.value;
const newTitle = titleText.textContent;
const newDesc = descText.textContent;
const newCategory = categorySelect.value;
await updateTicket({ status: newStatus, priority: newPriority, title: newTitle, description: newDesc, category: newCategory });
if (!confirm('Close this ticket?')) return;
await updateTicket({
status: 'Closed',
priority: priorityInput.value,
title: titleText.textContent,
description: descText.textContent,
category: categorySelect.value,
});
});
titleText.addEventListener('dblclick', () => {
@@ -195,6 +138,7 @@ document.addEventListener('DOMContentLoaded', async () => {
descInput.focus();
});
// Restore saved author name
const savedAuthor = localStorage.getItem('commentAuthor');
if (savedAuthor) commentAuthorInput.value = savedAuthor;
@@ -205,17 +149,16 @@ document.addEventListener('DOMContentLoaded', async () => {
const role = comment.role || 'user';
const isAdmin = role === 'admin';
const avatarUrl = isAdmin ? '/assets/admin.jpg' : '/assets/user.jpg';
return `
<div class="comment ${isAdmin ? 'comment-admin' : ''}">
<img class="comment-avatar" src="${avatarUrl}" alt="${isAdmin ? 'Admin' : 'User'} Avatar">
<div class="comment-content">
<div class="comment-header">
<span class="comment-author">${comment.author}</span>
<span class="comment-author">${escapeHtml(comment.author)}</span>
${isAdmin ? '<span class="comment-role-badge">Admin</span>' : ''}
<span class="comment-date">${formatDateTime(comment.date)}</span>
</div>
<div class="comment-text">${comment.content}</div>
<div class="comment-text">${linkify(comment.content)}</div>
</div>
</div>`;
}).join('');
@@ -228,10 +171,10 @@ document.addEventListener('DOMContentLoaded', async () => {
<div class="history-item">
<div class="history-icon"><i class="fas fa-${getHistoryIcon(h.action)}"></i></div>
<div class="history-content">
<div class="history-action">${h.action}</div>
<div class="history-details">${h.message || ''}</div>
<div class="history-action">${escapeHtml(h.action)}</div>
<div class="history-details">${escapeHtml(h.message || '')}</div>
<div class="history-meta">
<span>By ${h.author || h.actor || 'unknown'}</span>
<span>By ${escapeHtml(h.author || h.actor || 'unknown')}</span>
<span>${formatDateTime(h.date || h.timestamp)}</span>
</div>
</div>
@@ -240,20 +183,14 @@ document.addEventListener('DOMContentLoaded', async () => {
commentForm.addEventListener('submit', async (e) => {
e.preventDefault();
const author = commentAuthorInput.value.trim();
if (!author) return alert('Bitte gib deinen Namen ein');
if (!author) return alert('Please enter your name');
const content = document.getElementById('comment-content').value.trim();
if (!content) return alert('Comment required');
const role = 'admin';
const timestamp = new Date().toISOString();
try {
await createComment(ticketId, { author, role, content, timestamp });
await sendWebhook(`New comment added by ${author} (${role}): "${content}" on ticket #${ticketId}`);
await createComment(ticketId, { author, role: 'admin', content, timestamp: new Date().toISOString() });
localStorage.setItem('commentAuthor', author);
document.getElementById('comment-content').value = '';
await loadComments();
await loadHistory();
@@ -269,41 +206,30 @@ document.addEventListener('DOMContentLoaded', async () => {
const comment = document.getElementById('time-comment').value.trim();
const actor = commentAuthorInput.value || 'Admin';
if (isNaN(minutes) || minutes <= 0) return alert('Gültige Zeit in Minuten eingeben');
if (isNaN(minutes) || minutes <= 0) return alert('Enter valid minutes');
try {
// Save the time log
await logTime(ticketId, { minutes, comment, author: actor });
// Also add it as a comment
const timeComment = `⏱ Zeit gebucht: ${formatMinutes(minutes)}${comment ? ` – ${comment}` : ''}`;
await createComment(ticketId, {
author: actor,
role: 'admin',
content: timeComment,
timestamp: new Date().toISOString()
});
const timeComment = `⏱ Time booked: ${formatMinutes(minutes)}${comment ? ` – ${comment}` : ''}`;
await createComment(ticketId, { author: actor, role: 'admin', content: timeComment, timestamp: new Date().toISOString() });
// Webhook notification
await sendWebhook(`Time booked: ${formatMinutes(minutes)} by ${actor} on ticket #${ticketId}${comment ? ` – "${comment}"` : ''}`);
// Clear inputs and reload
document.getElementById('time-minutes').value = '';
document.getElementById('time-comment').value = '';
await loadPage();
} catch (err) {
console.error('Fehler beim Speichern der Zeit:', err);
alert('Fehler beim Speichern');
console.error('Error saving time:', err);
alert('Error saving time');
}
});
// Tabs
document.querySelectorAll('.tab-btn').forEach(btn => {
btn.addEventListener('click', () => {
const tab = btn.dataset.tab;
document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
btn.classList.add('active');
document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active'));
document.getElementById(`${tab}-tab`).classList.add('active');
document.getElementById(`${btn.dataset.tab}-tab`).classList.add('active');
});
});
+16 -7
View File
@@ -17,7 +17,6 @@ export async function fetchHistory(id) {
}
export async function logTime(id, timeLog) {
// timeLog = { minutes: Number, comment: String, author: String }
const res = await fetch(`/api/tickets/${id}/time`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
@@ -26,7 +25,6 @@ export async function logTime(id, timeLog) {
return res.json();
}
// Flexible Update-Funktion für beliebige Felder, z.B. {status, priority, category, actor, ...}
export async function updateTicket(id, data) {
const res = await fetch(`/api/tickets/${id}`, {
method: 'PUT',
@@ -45,15 +43,26 @@ export async function createComment(id, comment) {
return res.json();
}
// XSS protection — escape HTML entities before inserting into innerHTML
export function escapeHtml(str) {
if (!str) return '';
const div = document.createElement('div');
div.textContent = str;
return div.innerHTML;
}
// Convert URLs in text to clickable links (applied AFTER escaping)
export function linkify(text) {
const escaped = escapeHtml(text);
const urlPattern = /(\bhttps?:\/\/[^\s<]+)/g;
return escaped.replace(urlPattern, '<a href="$1" target="_blank" rel="noopener noreferrer">$1</a>');
}
export function formatDateTime(date) {
if (!date) return 'n/a';
// Convert SQLite DATETIME if needed
const safeDate = date.includes('T') ? date : date.replace(' ', 'T');
const parsed = new Date(safeDate + 'Z'); // Assume UTC
const parsed = new Date(safeDate + 'Z');
if (isNaN(parsed.getTime())) return 'n/a';
return parsed.toLocaleString(undefined, {
year: 'numeric',
month: 'short',
+16 -82
View File
@@ -1,16 +1,14 @@
import {
fetchTicket, fetchComments, fetchHistory,
createComment,
formatDateTime, formatMinutes, getHistoryIcon
fetchTicket, fetchComments, fetchHistory, createComment,
formatDateTime, formatMinutes, getHistoryIcon, escapeHtml, linkify
} from './ticket-shared.js';
document.addEventListener('DOMContentLoaded', () => {
document.body.classList.add('user-view');
const ticketId = new URLSearchParams(window.location.search).get('id');
if (!ticketId) return window.location.href = '/';
if (!ticketId) return (window.location.href = '/');
// DOM elements
const ticketTitle = document.getElementById('ticket-title-text');
const ticketIdElem = document.getElementById('ticket-id-val');
const ticketStatus = document.getElementById('ticket-status-badge');
@@ -24,54 +22,6 @@ document.addEventListener('DOMContentLoaded', () => {
const historyContainer = document.getElementById('history-container');
const commentForm = document.getElementById('comment-form');
const tabBtns = document.querySelectorAll('.tab-btn');
const totalTimeDisplay = document.getElementById('total-time');
let webhookConfig = null;
// Fetch Webhook Configuration
async function loadWebhookConfig() {
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 } };
}
}
// Send Webhook Notification
async function sendAdminWebhook(message) {
if (!webhookConfig?.admin) {
console.log('Admin webhook not configured, skipping notification');
return;
}
try {
const res = await fetch(webhookConfig.admin, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ content: message })
});
if (!res.ok) {
console.error('Admin webhook failed:', res.statusText);
}
} catch (err) {
console.error('Error sending admin webhook:', err);
}
}
// Links automatically convert to clickable
function linkify(text) {
const urlPattern = /(\bhttps?:\/\/[^\s<]+)/g;
return text.replace(urlPattern, '<a href="$1" target="_blank" rel="noopener noreferrer">$1</a>');
}
let originalStatus = '';
let originalPriority = '';
@@ -89,16 +39,12 @@ document.addEventListener('DOMContentLoaded', () => {
ticketUpdated.textContent = formatDateTime(ticket.updated_at);
ticketPriority.textContent = ticket.priority;
if (ticketCategory) {
ticketCategory.textContent = ticket.category || '—';
}
if (ticketCategory) ticketCategory.textContent = ticket.category || '—';
ticketStatus.className = `ticket-status status-${ticket.status.replace(/ /g, '-')}`;
const totalTimeDisplay = document.getElementById('total-time');
if (totalTimeDisplay) {
totalTimeDisplay.textContent = formatMinutes(ticket.total_time || 0);
}
if (totalTimeDisplay) totalTimeDisplay.textContent = formatMinutes(ticket.total_time || 0);
originalStatus = ticket.status;
originalPriority = ticket.priority;
@@ -110,20 +56,16 @@ document.addEventListener('DOMContentLoaded', () => {
const role = comment.role ? comment.role.toLowerCase() : 'user';
let avatarUrl = '/assets/user.jpg';
if (role === 'admin') avatarUrl = '/assets/admin.jpg';
else if (role === 'moderator') avatarUrl = '/assets/moderator.jpg';
// Comment content is linkified
const linkedContent = linkify(comment.content || '');
return `
<div class="comment">
<img class="comment-avatar" src="${avatarUrl}" alt="${role.charAt(0).toUpperCase() + role.slice(1)} Avatar">
<div class="comment-content">
<div class="comment-header">
<span class="comment-author">${comment.author}</span>
<span class="comment-author">${escapeHtml(comment.author)}</span>
<span class="comment-date">${formatDateTime(comment.date)}</span>
</div>
<div class="comment-text">${linkedContent}</div>
<div class="comment-text">${linkify(comment.content)}</div>
</div>
</div>
`;
@@ -136,10 +78,10 @@ document.addEventListener('DOMContentLoaded', () => {
<div class="history-item">
<div class="history-icon"><i class="fas fa-${getHistoryIcon(h.action)}"></i></div>
<div class="history-content">
<div class="history-action">${h.action}</div>
<div class="history-details">${h.message || h.details || ''}</div>
<div class="history-action">${escapeHtml(h.action)}</div>
<div class="history-details">${escapeHtml(h.message || h.details || '')}</div>
<div class="history-meta">
<span class="history-actor">By ${h.author || h.actor || 'unknown'}</span>
<span class="history-actor">By ${escapeHtml(h.author || h.actor || 'unknown')}</span>
<span class="history-date">${formatDateTime(h.date)}</span>
</div>
</div>
@@ -154,14 +96,12 @@ document.addEventListener('DOMContentLoaded', () => {
const content = document.getElementById('comment-content')?.value;
if (!content?.trim()) return alert('Please enter a comment');
const timestamp = new Date().toISOString();
try {
await createComment(ticketId, { author, content, timestamp });
await createComment(ticketId, { author, content, timestamp: new Date().toISOString() });
// Webhook notification is handled server-side
document.getElementById('comment-content').value = '';
await loadComments();
await loadHistory();
await sendAdminWebhook(`New comment added by ${author}: "${content}" on ticket #${ticketId}`);
} catch (err) {
console.error('Failed to create comment:', err);
alert('Failed to submit comment. Please try again.');
@@ -173,19 +113,15 @@ document.addEventListener('DOMContentLoaded', () => {
const ticket = await fetchTicket(ticketId);
if (!ticket) return;
// Update UI if status or priority changes server-side
if (ticket.status !== originalStatus) {
originalStatus = ticket.status;
ticketStatus.textContent = ticket.status;
ticketStatus.className = `ticket-status status-${ticket.status.replace(/ /g, '-')}`;
}
if (ticket.priority !== originalPriority) {
originalPriority = ticket.priority;
ticketPriority.textContent = ticket.priority;
}
// Check and update category if necessary
if (ticketCategory && ticket.category !== ticketCategory.textContent) {
ticketCategory.textContent = ticket.category || '—';
}
@@ -199,12 +135,10 @@ document.addEventListener('DOMContentLoaded', () => {
}));
// Initial load
loadWebhookConfig().then(() => {
loadTicketDetails();
loadComments();
loadHistory();
});
loadTicketDetails();
loadComments();
loadHistory();
// Periodic updates
// Poll for changes every 30s
setInterval(checkForChanges, 30000);
});
+4 -25
View File
@@ -7,10 +7,7 @@
<link rel="icon" type="image/x-icon" href="/assets/favicon_ticket.ico">
<link rel="stylesheet" href="ticket-view.css" />
<link rel="stylesheet" href="admin-view.css" />
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css"
/>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" />
</head>
<body>
<div class="container">
@@ -25,7 +22,6 @@
<main class="main-content">
<div class="ticket-details-layout">
<!-- Ticket Info Section -->
<section class="ticket-details">
<div class="ticket-header">
<div id="ticket-title-view">
@@ -42,28 +38,23 @@
<h4>Requester</h4>
<p id="ticket-requester">-</p>
</div>
<div class="info-item description">
<h3>Description</h3>
<p id="ticket-description-text">Loading...</p>
<textarea id="ticket-description-input" class="form-control" style="display: none"></textarea>
</div>
<div class="info-item created">
<h4>Created</h4>
<p id="ticket-created">-</p>
</div>
<div class="info-item updated">
<h4>Last Updated</h4>
<p id="ticket-updated">-</p>
</div>
<div class="info-item">
<h4>Time</h4>
<p><span id="total-time">0</span></p>
</div>
<div class="info-item status">
<h4><label for="status-select">Status</label></h4>
<select id="status-select" class="form-control">
@@ -73,7 +64,6 @@
<option value="Closed">Closed</option>
</select>
</div>
<div class="info-item priority">
<h4><label for="priority-text">Priority</label></h4>
<select id="priority-text" class="form-control">
@@ -83,16 +73,10 @@
<option value="Urgent">Urgent</option>
</select>
</div>
<div class="info-item category">
<h4><label for="category-select">Category</label></h4>
<select id="category-select" class="form-control">
<option value="HELP">HELP</option>
<option value="HELP MEE NOOOW">HELP MEE NOOOW</option>
<option value="IT-Support">IT-Support</option>
<option value="Suggestion...">Suggestion...</option>
<option value="Add Book pls">Add Book pls</option>
<option value="Honeyycloud!">Honeyycloud!</option>
<!-- Populated dynamically -->
</select>
</div>
</div>
@@ -107,7 +91,6 @@
</div>
</section>
<!-- Ticket Activity Section -->
<section class="ticket-activity">
<div class="tabs">
<button class="tab-btn active" data-tab="comments">Comments</button>
@@ -121,18 +104,13 @@
<textarea id="comment-content" rows="2" placeholder="Add a comment..." required></textarea>
<button class="btn-primary" type="submit">Post Comment</button>
</form>
<form id="time-booking-form" class="comment-form compact-form">
<input type="number" id="time-minutes" name="time-minutes" min="0" placeholder="Minutes" required />
<textarea id="time-comment" name="time-comment" rows="2" placeholder="Optional comment"></textarea>
<button class="btn-primary" type="submit">Add Time</button>
</form>
</div>
<!-- Comment Output -->
<div id="comments-container"></div>
<!-- Time Logs -->
<section id="time-logs" class="time-logs"></section>
</div>
@@ -144,10 +122,11 @@
</main>
<footer class="footer">
<p>Ticket System by Honey v1.1 © 2025</p>
<p class="app-footer-text"></p>
</footer>
</div>
<script type="module" src="ticket-admin.js"></script>
<script src="../version.js"></script>
</body>
</html>
+2 -1
View File
@@ -110,10 +110,11 @@
</main>
<footer class="footer">
<p>Ticket System by Honey v1.1 © 2025</p>
<p class="app-footer-text"></p>
</footer>
</div>
<script type="module" src="ticket-user.js"></script>
<script src="../version.js"></script>
</body>
</html>