diff --git a/SharpbinV2.Server/Controllers/PasteController.cs b/SharpbinV2.Server/Controllers/PasteController.cs index c7cfc68..edf30c3 100644 --- a/SharpbinV2.Server/Controllers/PasteController.cs +++ b/SharpbinV2.Server/Controllers/PasteController.cs @@ -308,7 +308,7 @@ namespace SharpbinV2.Server.Controllers int pages = await _databaseService.EnumerateUserPastes(user) / limit; if (page > pages) return BadRequest(new { success = false, message = "Page number exceeds available pages." }); - List? pastes = await _databaseService.GetPastesFromUser(user, limit, page, _logger); + List? pastes = await _databaseService.GetPastesFromUser(user, limit, page, _logger, true); if (pastes == null || pastes.Count == 0) return NotFound(new { success = false, message = "No pastes found." }); var pasteList = new List(); diff --git a/SharpbinV2.Server/Services/DatabaseService.cs b/SharpbinV2.Server/Services/DatabaseService.cs index 535dfc4..34347c7 100644 --- a/SharpbinV2.Server/Services/DatabaseService.cs +++ b/SharpbinV2.Server/Services/DatabaseService.cs @@ -649,7 +649,7 @@ namespace SharpbinV2.Server.Services return null; } } - public async Task?> GetPastesFromUser(User user, int limit, int page, ILogger logger) + public async Task?> GetPastesFromUser(User user, int limit, int page, ILogger logger, bool _private = false) { if (user == null || limit <= 0 || page < 0) return null; @@ -660,10 +660,15 @@ namespace SharpbinV2.Server.Services await connection.OpenAsync(); using (var command = connection.CreateCommand()) { - command.CommandText = "SELECT * FROM pastes WHERE AuthorUUID = @AuthorUUID ORDER BY Created DESC LIMIT @Limit OFFSET @Offset;"; + if (_private) + command.CommandText = "SELECT * FROM pastes WHERE AuthorUUID = @AuthorUUID ORDER BY Created DESC LIMIT @Limit OFFSET @Offset;"; + else + command.CommandText = "SELECT * FROM pastes WHERE AuthorUUID = @AuthorUUID AND Visibility NOT IN (1,2) ORDER BY Created DESC LIMIT @Limit OFFSET @Offset;"; + command.Parameters.AddWithValue("@AuthorUUID", user.UUID); command.Parameters.AddWithValue("@Limit", limit); command.Parameters.AddWithValue("@Offset", limit * page); + using (var reader = await command.ExecuteReaderAsync()) { if (!reader.HasRows) diff --git a/SharpbinV2.Server/wwwroot/css/dash.css b/SharpbinV2.Server/wwwroot/css/dash.css index 82c6e75..dc8205c 100644 --- a/SharpbinV2.Server/wwwroot/css/dash.css +++ b/SharpbinV2.Server/wwwroot/css/dash.css @@ -1,3 +1,25 @@ +::selection { + background-color: var(--neutral-600); + color: var(--neutral-100); +} + +::-moz-selection { + background-color: var(--neutral-600); + color: var(--neutral-100); +} + +input::selection, +textarea::selection { + background-color: #3b82f6; + color: white; +} + +input::-moz-selection, +textarea::-moz-selection { + background-color: #3b82f6; + color: white; +} + body { background-color: var(--neutral-950); color: var(--neutral-100); diff --git a/SharpbinV2.Server/wwwroot/dash.html b/SharpbinV2.Server/wwwroot/dash.html index 15ffa9d..33f13cb 100644 --- a/SharpbinV2.Server/wwwroot/dash.html +++ b/SharpbinV2.Server/wwwroot/dash.html @@ -47,6 +47,7 @@ + \ No newline at end of file diff --git a/SharpbinV2.Server/wwwroot/js/dash.js b/SharpbinV2.Server/wwwroot/js/dash.js index a346fb7..aac90e7 100644 --- a/SharpbinV2.Server/wwwroot/js/dash.js +++ b/SharpbinV2.Server/wwwroot/js/dash.js @@ -179,84 +179,90 @@ function nextPage() { } -function logout() { - - if (document.querySelector('.logout-modal-overlay')) return; - - const modalOverlay = document.createElement('div'); - modalOverlay.className = 'logout-modal-overlay'; - - const modalBox = document.createElement('div'); - modalBox.className = 'logout-modal-box'; - modalBox.innerHTML = ` -

Confirm Logout

-

Are you sure you want to log out?

- - - `; - modalOverlay.appendChild(modalBox); - document.body.appendChild(modalOverlay); - - document.getElementById('cancel-logout').onclick = function () { - document.body.removeChild(modalOverlay); - }; - - document.getElementById('confirm-logout').onclick = async function () { +async function logout() { + const confirmed = await Modal.confirm( + "Are you sure you want to log out?", + "Confirm Logout", + "danger" + ); + + if (confirmed) { try { - await fetch('/api/auth/logout', { method: 'POST'}); + await fetch('/api/auth/logout', { method: 'POST' }); } catch { } window.location.href = '/login'; - }; + } } -function deleteAccount() { - - if (document.querySelector('.delete-modal-overlay')) return; - +async function deleteAccount() { const username = document.getElementById('account-username').textContent.replace('Username: ', '').trim(); const pasteCount = userPastes.length; - const modalOverlay = document.createElement('div'); - modalOverlay.className = 'delete-modal-overlay'; - - const modalBox = document.createElement('div'); - modalBox.className = 'delete-modal-box'; - modalBox.innerHTML = ` -

Delete Account

-

This action is irreversible and will delete your account and all your ${pasteCount} pastes.

-

Type your username ${username} and your paste count ${pasteCount} to confirm:

-
-
- - - + const customContent = document.createElement('div'); + customContent.innerHTML = ` +

+ This action is irreversible and will delete your account and all your ${pasteCount} pastes. +

+

+ To confirm, type your username ${username} and your paste count ${pasteCount}: +

+
+ + +
+
+ + +
+
+ + +
`; - modalOverlay.appendChild(modalBox); - document.body.appendChild(modalOverlay); - document.getElementById('cancel-delete-account').onclick = function () { - document.body.removeChild(modalOverlay); - }; + const { body, close } = Modal.custom(customContent, { + title: 'Delete Account', + className: 'modal-delete-account' + }); + + const userInput = customContent.querySelector('#delete-username'); + const countInput = customContent.querySelector('#delete-pastecount'); + const confirmBtn = customContent.querySelector('.delete-confirm'); + const cancelBtn = customContent.querySelector('.delete-cancel'); - const userInput = document.getElementById('delete-username'); - const countInput = document.getElementById('delete-pastecount'); - const confirmBtn = document.getElementById('confirm-delete-account'); function validateInputs() { - if (userInput.value.trim() === username && countInput.value.trim() === String(pasteCount)) { + const usernameValid = userInput.value.trim() === username; + const countValid = countInput.value.trim() === String(pasteCount); + + if (usernameValid && countValid) { confirmBtn.disabled = false; + confirmBtn.style.opacity = '1'; } else { confirmBtn.disabled = true; + confirmBtn.style.opacity = '0.6'; } } + + validateInputs(); + userInput.addEventListener('input', validateInputs); countInput.addEventListener('input', validateInputs); + cancelBtn.onclick = () => close(); + confirmBtn.onclick = async function () { if (confirmBtn.disabled) return; + + if (userInput.value.trim() !== username || countInput.value.trim() !== String(pasteCount)) { + return; + } + try { - await fetch('/api/auth/delete', { method: 'DELETE'}); + await fetch('/api/auth/delete', { method: 'DELETE' }); } catch { } window.location.href = '/register'; }; + + setTimeout(() => userInput.focus(), 100); } \ No newline at end of file diff --git a/SharpbinV2.Server/wwwroot/js/main.js b/SharpbinV2.Server/wwwroot/js/main.js index d3975ab..e64c304 100644 --- a/SharpbinV2.Server/wwwroot/js/main.js +++ b/SharpbinV2.Server/wwwroot/js/main.js @@ -305,4 +305,6 @@ function showNotification(message, type = 'info', duration = 3000) { } }, 300); }, duration); -} \ No newline at end of file +} + + \ No newline at end of file diff --git a/SharpbinV2.Server/wwwroot/js/modal.js b/SharpbinV2.Server/wwwroot/js/modal.js new file mode 100644 index 0000000..64e1651 --- /dev/null +++ b/SharpbinV2.Server/wwwroot/js/modal.js @@ -0,0 +1,707 @@ +const Modal = { + createModal(options = {}) { + const { + id = 'modal-' + Date.now(), + title = '', + className = '', + closable = true, + backdrop = true, + noAnimation = false + } = options; + + this.removeModal(id); + + const modalBg = this.createElement('div', { + id: id + '-bg', + className: `modal-backdrop ${className} ${noAnimation ? 'no-animation' : ''}`, + style: backdrop ? '' : 'pointer-events: none;' + }); + + const modal = this.createElement('div', { + className: `modal ${noAnimation ? 'no-animation' : ''}`, + style: 'pointer-events: auto;' + }); + + if (title) { + const header = this.createElement('div', { + className: 'modal-header', + innerHTML: ` + + ${closable ? '' : ''} + ` + }); + modal.appendChild(header); + } + + const body = this.createElement('div', { className: 'modal-body' }); + modal.appendChild(body); + + modalBg.appendChild(modal); + document.body.appendChild(modalBg); + + this.addModalStyles(); + + const closeModal = () => this.removeModal(id); + + if (closable) { + const closeBtn = modal.querySelector('.modal-close'); + if (closeBtn) closeBtn.onclick = closeModal; + + modal.addEventListener('keydown', e => { + if (e.key === 'Escape') closeModal(); + }); + + if (backdrop) { + modalBg.addEventListener('click', e => { + if (e.target === modalBg) closeModal(); + }); + } + } + + modal.querySelector('.modal-body').focus = () => { + const focusable = modal.querySelector('input, select, textarea, button'); + if (focusable) focusable.focus(); + }; + + setTimeout(() => modal.querySelector('.modal-body').focus(), 100); + + return { + modal, + body: modal.querySelector('.modal-body'), + close: closeModal, + updateContent: (newContent) => { + const body = modal.querySelector('.modal-body'); + if (typeof newContent === 'string') { + body.innerHTML = newContent; + } else if (newContent instanceof HTMLElement) { + body.innerHTML = ''; + body.appendChild(newContent); + } + + setTimeout(() => { + const focusable = body.querySelector('input, select, textarea, button'); + if (focusable) focusable.focus(); + }, 50); + } + }; + }, + + createElement(tag, props = {}) { + const element = document.createElement(tag); + Object.assign(element, props); + return element; + }, + + removeModal(id) { + const existingModal = document.getElementById(id + '-bg'); + if (existingModal) existingModal.remove(); + }, + + confirm(message, title = 'Confirm', type = 'default') { + return new Promise((resolve) => { + const { body, close } = this.createModal({ title, className: `modal-confirm modal-confirm-${type}` }); + + const confirmButtonClass = type === 'danger' ? 'btn-danger' : 'btn-primary'; + + body.innerHTML = ` + + + `; + + const handleResult = (result) => { + close(); + resolve(result); + }; + + body.querySelector('.modal-cancel').onclick = () => handleResult(false); + body.querySelector('.modal-confirm-btn').onclick = () => handleResult(true); + + body.addEventListener('keydown', e => { + if (e.key === 'Enter') handleResult(true); + else if (e.key === 'Escape') handleResult(false); + }); + }); + }, + + prompt(message, defaultValue = '', title = 'Input', inputType = 'text', options = {}) { + return new Promise((resolve) => { + const { keepOpen = false } = options; + const { body, close, updateContent } = this.createModal({ + title, + className: 'modal-prompt', + ...options + }); + + const createPromptContent = (message, defaultValue = '', clearValue = false) => { + const inputId = 'modal-input-' + Date.now(); + return ` + + + + `; + }; + + body.innerHTML = createPromptContent(message, defaultValue); + + const handleResult = (result) => { + if (!keepOpen) { + close(); + } + resolve(result); + }; + + const setupEventListeners = () => { + const input = body.querySelector('.modal-input'); + const cancelBtn = body.querySelector('.modal-cancel'); + const okBtn = body.querySelector('.modal-ok'); + + const newCancelBtn = cancelBtn.cloneNode(true); + const newOkBtn = okBtn.cloneNode(true); + cancelBtn.parentNode.replaceChild(newCancelBtn, cancelBtn); + okBtn.parentNode.replaceChild(newOkBtn, okBtn); + + newCancelBtn.onclick = () => handleResult(null); + newOkBtn.onclick = () => handleResult(input.value); + + input.addEventListener('keydown', e => { + if (e.key === 'Enter') handleResult(input.value); + else if (e.key === 'Escape') handleResult(null); + }); + + input.focus(); + input.select(); + }; + + setupEventListeners(); + + if (keepOpen) { + resolve({ + value: null, + update: (newMessage, clearInput = true) => { + return new Promise((updateResolve) => { + updateContent(createPromptContent(newMessage, defaultValue, clearInput)); + + const handleUpdateResult = (result) => { + updateResolve(result); + }; + + const setupUpdateListeners = () => { + const input = body.querySelector('.modal-input'); + const cancelBtn = body.querySelector('.modal-cancel'); + const okBtn = body.querySelector('.modal-ok'); + + cancelBtn.onclick = () => handleUpdateResult(null); + okBtn.onclick = () => handleUpdateResult(input.value); + + input.addEventListener('keydown', e => { + if (e.key === 'Enter') handleUpdateResult(input.value); + else if (e.key === 'Escape') handleUpdateResult(null); + }); + + input.focus(); + input.select(); + }; + + setupUpdateListeners(); + }); + }, + close + }); + } + }); + }, + + select(message, options = [], title = 'Select') { + return new Promise((resolve) => { + const { body, close } = this.createModal({ title, className: 'modal-select' }); + + const selectId = 'modal-select-' + Date.now(); + const optionsHtml = options.map(opt => { + const value = typeof opt === 'object' ? opt.value : opt; + const label = typeof opt === 'object' ? opt.label : opt; + return ``; + }).join(''); + + body.innerHTML = ` + + + + `; + + const select = body.querySelector('.modal-select-input'); + const handleResult = (result) => { + close(); + resolve(result); + }; + + body.querySelector('.modal-cancel').onclick = () => handleResult(null); + body.querySelector('.modal-ok').onclick = () => handleResult(select.value); + + select.addEventListener('keydown', e => { + if (e.key === 'Enter') handleResult(select.value); + else if (e.key === 'Escape') handleResult(null); + }); + + select.focus(); + }); + }, + + date(message, defaultDate = '', title = 'Select Date') { + return new Promise((resolve) => { + const { body, close } = this.createModal({ title, className: 'modal-date' }); + + const inputId = 'modal-date-' + Date.now(); + const dateValue = defaultDate || new Date().toISOString().split('T')[0]; + + body.innerHTML = ` + + + + `; + + const input = body.querySelector('.modal-input'); + const handleResult = (result) => { + close(); + resolve(result); + }; + + body.querySelector('.modal-cancel').onclick = () => handleResult(null); + body.querySelector('.modal-ok').onclick = () => handleResult(input.value); + + input.addEventListener('keydown', e => { + if (e.key === 'Enter') handleResult(input.value); + else if (e.key === 'Escape') handleResult(null); + }); + + input.focus(); + }); + }, + + form(fields = [], title = 'Form') { + return new Promise((resolve) => { + const { body, close } = this.createModal({ title, className: 'modal-form' }); + + const formHtml = fields.map((field, index) => { + const id = `modal-field-${Date.now()}-${index}`; + const { + type = 'text', + label = '', + name = `field_${index}`, + value = '', + required = false, + options = [] + } = field; + + let inputHtml = ''; + switch (type) { + case 'select': + const optionsHtml = options.map(opt => { + const optValue = typeof opt === 'object' ? opt.value : opt; + const optLabel = typeof opt === 'object' ? opt.label : opt; + return ``; + }).join(''); + inputHtml = ``; + break; + case 'textarea': + inputHtml = ``; + break; + case 'checkbox': + inputHtml = ``; + break; + default: + inputHtml = ``; + } + + return ` + + `; + }).join(''); + + body.innerHTML = ` + + `; + + const form = body.querySelector('.modal-form-content'); + const handleResult = (result) => { + close(); + resolve(result); + }; + + body.querySelector('.modal-cancel').onclick = () => handleResult(null); + + form.addEventListener('submit', e => { + e.preventDefault(); + const formData = new FormData(form); + const result = {}; + + fields.forEach(field => { + const name = field.name || `field_${fields.indexOf(field)}`; + if (field.type === 'checkbox') { + result[name] = formData.has(name); + } else { + result[name] = formData.get(name); + } + }); + + handleResult(result); + }); + + const firstInput = body.querySelector('.modal-input'); + if (firstInput) firstInput.focus(); + }); + }, + + alert(message, title = 'Alert', type = 'info') { + return new Promise((resolve) => { + const { body, close } = this.createModal({ title, className: `modal-alert modal-alert-${type}` }); + + const icon = { + info: 'ℹ️', + warning: '⚠️', + error: '❌', + success: '✅' + }[type] || 'ℹ️'; + + body.innerHTML = ` + + + `; + + const handleResult = () => { + close(); + resolve(); + }; + + body.querySelector('.modal-ok').onclick = handleResult; + + body.addEventListener('keydown', e => { + if (e.key === 'Enter' || e.key === 'Escape') handleResult(); + }); + }); + }, + + custom(content, options = {}) { + const { body, close } = this.createModal(options); + + if (typeof content === 'string') { + body.innerHTML = content; + } else if (content instanceof HTMLElement) { + body.appendChild(content); + } + + return { body, close }; + }, + + addModalStyles() { + if (document.getElementById('modal-styles')) return; + + const style = document.createElement('style'); + style.id = 'modal-styles'; + style.textContent = ` + .modal ::selection { + background-color: var(--neutral-600, #525252); + color: var(--neutral-100, #f5f5f5); + } + + .modal ::-moz-selection { + background-color: var(--neutral-600, #525252); + color: var(--neutral-100, #f5f5f5); + } + + .modal input::selection, + .modal textarea::selection, + .modal-input::selection, + .modal-backdrop input::selection, + .modal-backdrop textarea::selection { + background-color: #3b82f6; + color: white; + } + + .modal input::-moz-selection, + .modal textarea::-moz-selection, + .modal-input::-moz-selection, + .modal-backdrop input::-moz-selection, + .modal-backdrop textarea::-moz-selection { + background-color: #3b82f6; + color: white; + } + + .modal-backdrop { + position: fixed; + top: 0; + left: 0; + width: 100%; + height: 100%; + background: rgba(0, 0, 0, 0.5); + display: flex; + justify-content: center; + align-items: center; + z-index: 999; + animation: modal-fade-in 0.2s ease-out; + } + + .modal-backdrop.no-animation { + animation: none; + } + + .modal { + background: var(--neutral-900, #1a1a1a); + border-radius: 8px; + box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04); + max-width: 500px; + width: 90%; + max-height: 80vh; + overflow-y: auto; + border: 1px solid var(--neutral-800, #333); + animation: modal-slide-in 0.2s ease-out; + } + + .modal.no-animation { + animation: none; + } + + .modal-header { + display: flex; + justify-content: space-between; + align-items: center; + padding: 1.5rem 1.5rem 1rem; + border-bottom: 1px solid var(--neutral-800, #333); + } + + .modal-title { + font-size: 1.25rem; + font-weight: 600; + color: var(--text-color, #fff); + margin: 0; + } + + .modal-close { + background: none; + border: none; + font-size: 1.5rem; + color: var(--text-color-secondary, #aaa); + cursor: pointer; + padding: 0; + width: 24px; + height: 24px; + display: flex; + align-items: center; + justify-content: center; + border-radius: 4px; + transition: all 0.2s ease; + } + + .modal-close:hover { + background: var(--neutral-800, #333); + color: var(--text-color, #fff); + } + + .modal-body { + padding: 1.5rem; + } + + .modal-label { + display: block; + font-weight: 500; + color: var(--text-color, #fff); + margin-bottom: 0.75rem; + font-size: 0.95rem; + } + + .modal-input, .modal-select-input { + width: 100%; + padding: 0.75rem; + border: 1px solid var(--neutral-700, #444); + border-radius: 6px; + background: var(--neutral-800, #2a2a2a); + color: var(--text-color, #fff); + font-size: 1rem; + transition: border-color 0.2s ease; + box-sizing: border-box; + } + + .modal-input:focus, .modal-select-input:focus { + outline: none; + border-color: var(--primary-color, #3b82f6); + box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1); + } + + textarea.modal-input { + resize: vertical; + min-height: 100px; + font-family: inherit; + } + + .modal-checkbox { + width: auto !important; + margin-right: 0.5rem; + accent-color: var(--primary-color, #3b82f6); + } + + .modal-field { + margin-bottom: 1.25rem; + } + + .modal-field:last-of-type { + margin-bottom: 1.5rem; + } + + .modal-message { + color: var(--text-color, #fff); + margin: 0 0 1.5rem 0; + line-height: 1.6; + font-size: 0.95rem; + } + + .modal-buttons { + display: flex; + gap: 0.75rem; + justify-content: flex-end; + margin-top: 1.5rem; + } + + .btn { + padding: 0.75rem 1.25rem; + border: none; + border-radius: 6px; + font-size: 0.9rem; + font-weight: 500; + cursor: pointer; + transition: all 0.2s ease; + min-width: 80px; + font-family: inherit; + } + + .btn-primary { + background: var(--primary-color, #3b82f6); + color: white; + } + + .btn-primary:hover { + background: var(--primary-hover, #2563eb); + transform: translateY(-1px); + } + + .btn-secondary { + background: var(--neutral-700, #444); + color: var(--text-color, #fff); + border: 1px solid var(--neutral-600, #555); + } + + .btn-secondary:hover { + background: var(--neutral-600, #555); + transform: translateY(-1px); + } + + .btn-danger { + background: #dc2626; + color: white; + } + + .btn-danger:hover { + background: #b91c1c; + transform: translateY(-1px); + } + + .modal-alert-content { + display: flex; + align-items: flex-start; + gap: 1rem; + margin-bottom: 1.5rem; + } + + .modal-alert-icon { + font-size: 1.5rem; + flex-shrink: 0; + margin-top: 0.1rem; + } + + .modal-confirm-danger .modal-title { + color: #fca5a5; + } + + .modal-confirm-danger .modal-message { + color: #f3f4f6; + } + + .modal-alert-error .modal-alert-icon { + filter: hue-rotate(0deg); + } + + .modal-alert-warning .modal-alert-icon { + filter: hue-rotate(45deg); + } + + .modal-alert-success .modal-alert-icon { + filter: hue-rotate(120deg); + } + + @keyframes modal-fade-in { + from { opacity: 0; } + to { opacity: 1; } + } + + @keyframes modal-slide-in { + from { + opacity: 0; + transform: translateY(-20px) scale(0.95); + } + to { + opacity: 1; + transform: translateY(0) scale(1); + } + } + + @media (max-width: 600px) { + .modal { + width: 95%; + max-height: 90vh; + } + + .modal-header, .modal-body { + padding-left: 1rem; + padding-right: 1rem; + } + + .modal-buttons { + flex-direction: column; + } + + .btn { + width: 100%; + } + } + `; + document.head.appendChild(style); + } +}; + +window.Modal = Modal; diff --git a/SharpbinV2.Server/wwwroot/js/paste.js b/SharpbinV2.Server/wwwroot/js/paste.js index b74f573..1919c96 100644 --- a/SharpbinV2.Server/wwwroot/js/paste.js +++ b/SharpbinV2.Server/wwwroot/js/paste.js @@ -1,190 +1,194 @@ const visibility = [{ id: 0, name: "Public" }, { id: 1, name: "Unlisted" }, { id: 2, name: "Private" }]; +let paste = null; + +const ELEMENTS = { + get: (id) => document.getElementById(id), + create: (tag, props = {}) => { + const element = document.createElement(tag); + Object.assign(element, props); + return element; + }, + setText: (id, text) => ELEMENTS.get(id).innerText = text, + setStyle: (id, styles) => Object.assign(ELEMENTS.get(id).style, styles), + hide: (id) => ELEMENTS.get(id).style.display = "none", + show: (id, display = "inline-block") => ELEMENTS.get(id).style.display = display +}; + document.addEventListener("DOMContentLoaded", async function () { const id = window.location.pathname.split("/")[1]; - const contentPromise = fetch(`/api/pastes/${id}`).then(response => response.text()); - const infoPromise = fetch(`/api/pastes/${id}/info`).then(response => response.json()); + const [content, info] = await Promise.all([ + fetch(`/api/pastes/${id}`).then(response => response.text()), + fetch(`/api/pastes/${id}/info`).then(response => response.json()) + ]); - const blur = document.createElement("div"); - blur.id = "blur"; + const blur = ELEMENTS.create("div", { id: "blur" }); blur.dataset.decrypted = "false"; document.body.appendChild(blur); - const blur2 = document.getElementById("blur"); - const [content, info] = await Promise.all([contentPromise, infoPromise]); - const paste = info.paste; - - function showPasswordModal(errorMsg = "") { - return new Promise((resolve, reject) => { - const oldModal = document.getElementById("password-modal-bg"); - if (oldModal) oldModal.remove(); - - const modalBg = document.createElement("div"); - modalBg.id = "password-modal-bg"; - - const modal = document.createElement("div"); - modal.id = "password-modal"; - - const title = document.createElement("div"); - title.innerText = "Private Paste"; - title.className = "modal-title"; - - const label = document.createElement("label"); - label.innerText = "Enter the password to view this paste:"; - label.htmlFor = "password-input"; - - const input = document.createElement("input"); - input.type = "password"; - input.id = "password-input"; - input.autocomplete = "current-password"; - - if (errorMsg) { - showNotification(errorMsg, "error", 3000); - } - - const btnRow = document.createElement("div"); - btnRow.className = "modal-btn-row"; - - const okBtn = document.createElement("button"); - okBtn.innerText = "Unlock"; - - const cancelBtn = document.createElement("button"); - cancelBtn.innerText = "Cancel"; - - btnRow.appendChild(cancelBtn); - btnRow.appendChild(okBtn); - - modal.appendChild(title); - modal.appendChild(label); - modal.appendChild(input); - modal.appendChild(btnRow); - modalBg.appendChild(modal); - document.body.appendChild(modalBg); - - input.focus(); - - function cleanup() { - if (modalBg.parentNode) modalBg.parentNode.removeChild(modalBg); - } - - okBtn.onclick = () => { - resolve(input.value); - }; - cancelBtn.onclick = () => { - cleanup(); - reject(new Error("User cancelled")); - }; - input.addEventListener("keydown", e => { - if (e.key === "Enter") { - okBtn.click(); - } else if (e.key === "Escape") { - cancelBtn.click(); - } - }); - modalBg.addEventListener("click", e => { - if (e.target === modalBg) { - cancelBtn.click(); - } - }); - }); - } - - if (paste.visibility === 2) { - let success = false; - let lastError = ""; - while (!success) { - try { - const password = await showPasswordModal(lastError); - const decrypted = await decryptAES(content, password); - blur2.dataset.decrypted = "true"; - addContent(decrypted, paste.syntax); - document.getElementById("password-modal-bg")?.remove(); - success = true; - } catch (error) { - if (error.message === "User cancelled") { - document.getElementById("password-modal-bg")?.remove(); - break; - } - lastError = "Failed to decrypt, invalid password, or invalid data."; - } - } - } else { - blur2.dataset.decrypted = "true"; - addContent(content, paste.syntax); + paste = info.paste; + const finalContent = paste.visibility === 2 ? await handlePrivatePaste(content) : content; + + if (finalContent) { + blur.dataset.decrypted = "true"; + addContent(finalContent, paste.syntax); } + document.title = `${paste.title} - Sharpbin`; addInfo(paste); }); -function addInfo(paste) { - document.getElementById("paste-title").innerText = paste.title; - document.getElementById("paste-date").innerText = `${convertUnixToLocal(paste.created)}`; - document.getElementById("paste-syntax").innerText = paste.syntax; - document.getElementById("paste-size").innerText = paste.size === 0 ? "" : formatSize(paste.size); - if (paste.size !== paste.trueSize && paste.trueSize) { - const sizeElem = document.getElementById("paste-size"); - sizeElem.classList.add("has-true-size-tooltip"); - let tooltip = document.createElement("div"); - tooltip.className = "true-size-tooltip"; - tooltip.innerText = `True size: ${formatSize(paste.trueSize)}`; - sizeElem.appendChild(tooltip); - sizeElem.onmouseenter = () => { tooltip.style.opacity = 1; }; - sizeElem.onmouseleave = () => { tooltip.style.opacity = 0; }; - } - document.getElementById("paste-author").innerText = paste.username; - document.getElementById("author-link").href = paste.username === "Anonymous" ? "" : `/u/${paste.username}`; - if (paste.username === "Anonymous") { - document.getElementById("author-link").innerText = "Anonymous"; - document.getElementById("author-link").href = ""; - document.getElementById("author-link").style.pointerEvents = "none"; - document.getElementById("author-link").style.cursor = "not-allowed"; - document.getElementById("author-link").style.color = "var(--text-color)"; - document.getElementById("author-link").style.textDecoration = "none"; - } - document.getElementById("paste-views").innerText = paste.views; - document.getElementById("info-throbber").style.display = "none"; - document.getElementById("copy-button").addEventListener("click", function () { - navigator.clipboard.writeText(window.location.href); - showNotification("Paste copied to clipboard!", "info", 2000); - }); - document.getElementById("download-button").addEventListener("click", function () { - const content = document.getElementById("paste-content").innerText; - const blob = new Blob([content], { type: "text/plain" }); - const url = URL.createObjectURL(blob); - const a = document.createElement("a"); - a.href = url; - a.download = `${paste.title}.txt`; - document.body.appendChild(a); - a.click(); - document.body.removeChild(a); - URL.revokeObjectURL(url); - showNotification("Paste downloaded!", "info", 2000); - }); - document.getElementById("raw-button").addEventListener("click", function () { - window.location.href = `/raw/${paste.id}`; - }); +async function handlePrivatePaste(content) { + try { + const modalController = await Modal.prompt( + "Enter the password to view this paste:", + "", + "Private Paste", + "password", + { keepOpen: true } + ); + while (true) { + try { + const password = await modalController.update("Enter the password to view this paste:"); + + if (password === null) { + modalController.close(); + return null; + } + + const decrypted = await decryptAES(content, password); + modalController.close(); + return decrypted; + } catch (error) { + showNotification("Incorrect password. Please try again.", "error", 3000); + } + } + } catch (error) { + console.error('Error in handlePrivatePaste:', error); + return null; + } +} + +function addInfo(paste) { + const isAnonymous = paste.username === "Anonymous"; + + ELEMENTS.setText("paste-title", paste.title); + ELEMENTS.setText("paste-date", convertUnixToLocal(paste.created)); + ELEMENTS.setText("paste-syntax", paste.syntax); + ELEMENTS.setText("paste-size", paste.size === 0 ? "" : formatSize(paste.size)); + + setupSizeTooltip(paste); + setupAuthorLink(paste, isAnonymous); + + ELEMENTS.setText("paste-views", paste.views); + ELEMENTS.hide("info-throbber"); + + setupActionButtons(paste); + setupDeleteButton(paste); +} + +function setupSizeTooltip(paste) { + if (paste.size !== paste.trueSize && paste.trueSize) { + const sizeElem = ELEMENTS.get("paste-size"); + sizeElem.classList.add("has-true-size-tooltip"); + const tooltip = ELEMENTS.create("div", { + className: "true-size-tooltip", + innerText: `True size: ${formatSize(paste.trueSize)}` + }); + sizeElem.appendChild(tooltip); + sizeElem.onmouseenter = () => tooltip.style.opacity = 1; + sizeElem.onmouseleave = () => tooltip.style.opacity = 0; + } +} + +function setupAuthorLink(paste, isAnonymous) { + const authorLink = ELEMENTS.get("author-link"); + ELEMENTS.setText("paste-author", paste.username); + + if (isAnonymous) { + Object.assign(authorLink, { + innerText: "Anonymous", + href: "" + }); + Object.assign(authorLink.style, { + pointerEvents: "none", + textDecoration: "none" + }); + } else { + authorLink.href = `/u/${paste.username}`; + } +} + +function setupActionButtons(paste) { + const actions = [ + { + id: "copy-button", + action: () => { + const content = ELEMENTS.get("paste-content").innerText; + navigator.clipboard.writeText(content); + showNotification("Paste copied to clipboard!", "info", 2000); + } + }, + { + id: "download-button", + action: () => downloadPaste(paste.title) + }, + { + id: "raw-button", + action: () => window.location.href = `/raw/${paste.id}` + } + ]; + + actions.forEach(({ id, action }) => { + ELEMENTS.get(id).addEventListener("click", action); + }); +} + +function downloadPaste(title) { + const content = ELEMENTS.get("paste-content").innerText; + const blob = new Blob([content], { type: "text/plain" }); + const url = URL.createObjectURL(blob); + const a = ELEMENTS.create("a", { + href: url, + download: `${title}.txt` + }); + + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + showNotification("Paste downloaded!", "info", 2000); +} + +function setupDeleteButton(paste) { waitForAuthData().then(() => { if (authData.user.uuid === paste.authorUUID || authData.user.type === 255) { - document.getElementById("delete-button").style.display = "inline-block"; - document.getElementById("delete-button").addEventListener("click", function () { - if (confirm("Are you sure you want to delete this paste?")) { - fetch(`/api/pastes/${paste.id}`, { - method: "DELETE" - }).then(response => { - if (response.ok) { - showNotification("Paste deleted!", "info", 2000); - window.location.href = "/"; - } else { - showNotification("Failed to delete paste.", "error", 2000); - } - }); + ELEMENTS.show("delete-button"); + ELEMENTS.get("delete-button").addEventListener("click", async () => { + const confirmed = await Modal.confirm( + "Are you sure you want to delete this paste? This action cannot be undone.", + "Delete Paste", + "danger" + ); + if (confirmed) { + deletePaste(paste.id); } }); } }); } +function deletePaste(pasteId) { + fetch(`/api/pastes/${pasteId}`, { method: "DELETE" }) + .then(response => { + const message = response.ok ? "Paste deleted!" : "Failed to delete paste."; + const type = response.ok ? "info" : "error"; + showNotification(message, type, 2000); + if (response.ok) window.location.href = "/"; + }); +} + function waitForAuthData() { return new Promise((resolve) => { const checkAuth = setInterval(() => { @@ -197,41 +201,49 @@ function waitForAuthData() { } function addContent(content, syntax) { - var code = document.createElement("code"); - code.textContent = content; - var pre = document.getElementById("paste-content"); + const code = ELEMENTS.create("code", { + textContent: content, + id: "paste-content" + }); + const pre = ELEMENTS.get("paste-content"); + pre.innerText = ""; pre.appendChild(code); pre.removeAttribute("id"); - code.id = "paste-content"; - code.classList.add("language-" + syntax === "plaintext" ? "none" : syntax); - if (syntax !== "plaintext" && syntax !== "none" && syntax !== "" && syntax !== null) { + + const isPlaintext = ["plaintext", "none", "", null].includes(syntax); + code.classList.add(`language-${isPlaintext ? "none" : syntax}`); + + if (!isPlaintext) { hljs.highlightElement(code); - document.getElementById("paste-content").style.padding = "0px" + code.style.padding = "0px"; } + hljs.lineNumbersBlock(code); - document.getElementById("content-throbber").style.display = "none"; + ELEMENTS.hide("content-throbber"); } async function decryptAES(content, password) { - const enc = new TextEncoder(); const rawData = atob(content); const rawDataArray = Uint8Array.from(rawData, c => c.charCodeAt(0)); - const salt = rawDataArray.slice(0, 16); - const iv = rawDataArray.slice(16, 28); - const ciphertext = rawDataArray.slice(28); + const [salt, iv, ciphertext] = [ + rawDataArray.slice(0, 16), + rawDataArray.slice(16, 28), + rawDataArray.slice(28) + ]; - const keyMaterial = await window.crypto.subtle.importKey( + const keyMaterial = await crypto.subtle.importKey( "raw", - enc.encode(password), + new TextEncoder().encode(password), { name: "PBKDF2" }, false, ["deriveKey"] ); - const key = await window.crypto.subtle.deriveKey( + + const key = await crypto.subtle.deriveKey( { name: "PBKDF2", - salt: salt, + salt, iterations: 100000, hash: "SHA-256" }, @@ -241,24 +253,19 @@ async function decryptAES(content, password) { ["decrypt"] ); - - const decrypted = await window.crypto.subtle.decrypt( - { - name: "AES-GCM", - iv: iv - }, + const decrypted = await crypto.subtle.decrypt( + { name: "AES-GCM", iv }, key, ciphertext ); + return new TextDecoder().decode(decrypted); } -function convertUnixToLocal(unix) { - return new Date(unix * 1000).toLocaleString(); -} +const convertUnixToLocal = (unix) => new Date(unix * 1000).toLocaleString(); -function formatSize(bytes) { - if (bytes < 1024) return bytes + ' B'; - if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(2) + ' KB'; - return (bytes / (1024 * 1024)).toFixed(2) + ' MB'; -} \ No newline at end of file +const formatSize = (bytes) => { + if (bytes < 1024) return `${bytes} B`; + if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(2)} KB`; + return `${(bytes / (1024 * 1024)).toFixed(2)} MB`; +}; \ No newline at end of file diff --git a/SharpbinV2.Server/wwwroot/js/user.js b/SharpbinV2.Server/wwwroot/js/user.js index f4ef614..acd1474 100644 --- a/SharpbinV2.Server/wwwroot/js/user.js +++ b/SharpbinV2.Server/wwwroot/js/user.js @@ -41,7 +41,7 @@ document.addEventListener("DOMContentLoaded", async function () { window.location.href = "/error?code=404&message=User not found"; return; } - const userInfoRes = await fetch(`/api/users/${username}`); + const userInfoRes = await fetch(`/api/users/username/${username}`); if (!userInfoRes.ok) { document.getElementById("user-name").innerText = "User not found"; document.getElementById("user-pastes-list").innerHTML = "

No user data.

"; diff --git a/SharpbinV2.Server/wwwroot/paste.html b/SharpbinV2.Server/wwwroot/paste.html index 7c3acfd..fdd0046 100644 --- a/SharpbinV2.Server/wwwroot/paste.html +++ b/SharpbinV2.Server/wwwroot/paste.html @@ -23,7 +23,7 @@

Title

- +
@@ -46,6 +46,7 @@
+ \ No newline at end of file