From 3814366b39d5ecefe6e881c4e5b5c507740091b5 Mon Sep 17 00:00:00 2001 From: Sergey Svinolobov Date: Wed, 26 Jun 2024 00:47:18 -0400 Subject: [PATCH] added new/changed files --- .htaccess | 4 ++ app.py | 25 ---------- auth.php | 32 ++++++------ checkUploadLimit.js | 77 +++++++++++++++++++++++++++++ checkUploadLimit.php | 44 +++++++++++++++++ config.php | 3 +- displayFileList.js | 22 +++++++++ file_list.php => getFileList.php | 30 +++++++----- getUploadSize.php | 15 ++++++ styles.css | 84 ++++++++++++++++++++++++++++++++ upload.js | 26 +--------- upload.php | 60 ++++++++++++++++++----- users.txt | 2 + 13 files changed, 335 insertions(+), 89 deletions(-) create mode 100644 .htaccess delete mode 100644 app.py create mode 100644 checkUploadLimit.js create mode 100644 checkUploadLimit.php rename file_list.php => getFileList.php (77%) create mode 100644 getUploadSize.php create mode 100644 styles.css create mode 100644 users.txt diff --git a/.htaccess b/.htaccess new file mode 100644 index 0000000..ef366fb --- /dev/null +++ b/.htaccess @@ -0,0 +1,4 @@ + + Order Allow,Deny + Deny from all + \ No newline at end of file diff --git a/app.py b/app.py deleted file mode 100644 index 51e5322..0000000 --- a/app.py +++ /dev/null @@ -1,25 +0,0 @@ -from flask import Flask, request, jsonify -import subprocess - -app = Flask(__name__) - -def authenticate(username, password): - command = f"echo {password} | su -c 'whoami' {username}" - try: - result = subprocess.run(command, shell=True, capture_output=True, text=True, check=True) - return result.stdout.strip() == username - except subprocess.CalledProcessError: - return False - -@app.route('/auth', methods=['POST']) -def auth(): - data = request.json - username = data.get('username') - password = data.get('password') - if authenticate(username, password): - return jsonify({"authenticated": True}), 200 - else: - return jsonify({"authenticated": False}), 401 - -if __name__ == '__main__': - app.run(host='0.0.0.0', port=7000) diff --git a/auth.php b/auth.php index c9df7ec..44cc007 100644 --- a/auth.php +++ b/auth.php @@ -1,25 +1,27 @@ $username, "password" => $password)); - $options = array( - 'http' => array( - 'header' => "Content-Type: application/json\r\n", - 'method' => 'POST', - 'content' => $data, - ), - ); - $context = stream_context_create($options); - $result = file_get_contents($url, false, $context); - $response = json_decode($result, true); + $filename = 'users.txt'; + $response = array('authenticated' => false); + + if (!file_exists($filename)) { + return $response; + } + + $lines = file($filename, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); + foreach ($lines as $line) { + list($fileUser, $filePass) = explode(':', $line, 2); + if ($username === $fileUser && $password === $filePass) { + $response['authenticated'] = true; + break; + } + } + return $response['authenticated']; } diff --git a/checkUploadLimit.js b/checkUploadLimit.js new file mode 100644 index 0000000..7de529f --- /dev/null +++ b/checkUploadLimit.js @@ -0,0 +1,77 @@ +document.addEventListener('DOMContentLoaded', () => { + const fileInput = document.getElementById('file'); + const uploadBtn = document.getElementById('uploadBtn'); + const uploadForm = document.getElementById('uploadFileForm'); + const statusMessage = document.getElementById('statusMessage'); + const progressBar = document.getElementById('progressBar'); + const progressRow = document.getElementById('progressRow'); + const fileName = document.getElementById('fileName'); + + function convertToBytes(size) { + const units = { 'G': 1024 * 1024 * 1024, 'M': 1024 * 1024, 'K': 1024 }; + const unit = size.slice(-1).toUpperCase(); + const number = parseFloat(size.slice(0, -1)); + return units[unit] ? number * units[unit] : number; + } + + fileInput.addEventListener('change', () => { + if (fileInput.files.length > 0) { + uploadBtn.disabled = false; + fileName.textContent = fileInput.files[0].name; + } else { + uploadBtn.disabled = true; + fileName.textContent = ''; + } + }); + + uploadBtn.addEventListener('click', () => { + const file = fileInput.files[0]; + if (!file) { + alert('No file selected.'); + return; + } + + fetch('get_upload_size.php') + .then(response => response.text()) + .then(currentSize => { + const totalUploadLimit = convertToBytes('20G'); // Replace '20G' with your dynamic limit + const newSize = parseInt(currentSize) + file.size; + + if (newSize > totalUploadLimit) { + alert('Upload denied. Total upload limit exceeded.'); + } else { + uploadFile(); + } + }) + .catch(error => { + console.error('Error fetching current upload size:', error); + alert('Error fetching current upload size.'); + }); + }); + + function uploadFile() { + const formData = new FormData(uploadForm); + progressRow.style.display = 'block'; + statusMessage.textContent = ''; + + $.ajax({ + url: 'upload.php', + type: 'POST', + data: formData, + contentType: false, + processData: false, + xhr: function() { + const xhr = new window.XMLHttpRequest(); + xhr.upload.addEventListener('progress', function(evt) { + if (evt.lengthComputable) { + const percentComplete = (evt.loaded / evt.total) * 100; + progressBar.style.width = percentComplete + '%'; + } + }, false); + return xhr; + }, + success: function(response) { + progressBar.style.width = '0%'; + progressRow.style.display = 'none'; + statusMessage.textContent = response; + uploadBtn.disabled = true; diff --git a/checkUploadLimit.php b/checkUploadLimit.php new file mode 100644 index 0000000..68f9942 --- /dev/null +++ b/checkUploadLimit.php @@ -0,0 +1,44 @@ +isFile()) { + $size += $file->getSize(); + } + } + return $size; +} + +$response = ['uploadAllowed' => false, 'message' => '']; +$fileSize = isset($_POST['fileSize']) ? (int)$_POST['fileSize'] : 1000000000000; + +$totalUploadLimit = convertToBytes(TOTAL_UPLOAD_SIZE); +$currentDirSize = getDirectorySize(UPLOAD_DIR); +$newSize = $currentDirSize + $fileSize; + +if ($newSize > $totalUploadLimit) { + $response['message'] = 'Upload denied. Total upload limit exceeded.'; + $_SESSION['uploadAllowed'] = false; +} else { + $response['message'] = 'Upload allowed. Starting upload...'; + $_SESSION['uploadAllowed'] = true; +} + +echo json_encode($response); +?> diff --git a/config.php b/config.php index 69ffb3d..f6cde15 100644 --- a/config.php +++ b/config.php @@ -1,8 +1,9 @@ \ No newline at end of file diff --git a/displayFileList.js b/displayFileList.js index 35e1006..cdc5991 100644 --- a/displayFileList.js +++ b/displayFileList.js @@ -6,6 +6,28 @@ let sortFunctions = { 'Upload Time': (a, b) => new Date(a.uploaded) - new Date(b.uploaded) }; +async function loadFileList() { + try { + const { username, password } = authCredentials; + console.log('Loading file list with credentials:', { username, password }); // Debugging + const response = await fetch('getFileList.php', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ username, password }), + }); + if (!response.ok) { + throw new Error(`HTTP error! status: ${response.status}`); + } + const fileList = await response.json(); + console.log('File list loaded:', fileList); // Debugging: Log the file list to the console + displayFileList(fileList); + } catch (error) { + console.error('Error loading file list:', error); // Debugging: Log any errors to the console + } +} + function displayFileList(fileList) { const fileListContainer = document.getElementById('fileList'); fileListContainer.innerHTML = ''; diff --git a/file_list.php b/getFileList.php similarity index 77% rename from file_list.php rename to getFileList.php index 67b145a..5f47283 100644 --- a/file_list.php +++ b/getFileList.php @@ -2,18 +2,22 @@ require_once 'config.php'; function authenticate($username, $password) { - $url = 'http://localhost:7000/auth'; - $data = json_encode(array("username" => $username, "password" => $password)); - $options = array( - 'http' => array( - 'header' => "Content-Type: application/json\r\n", - 'method' => 'POST', - 'content' => $data, - ), - ); - $context = stream_context_create($options); - $result = file_get_contents($url, false, $context); - $response = json_decode($result, true); + $filename = 'users.txt'; + $response = array('authenticated' => false); + + if (!file_exists($filename)) { + return $response; + } + + $lines = file($filename, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); + foreach ($lines as $line) { + list($fileUser, $filePass) = explode(':', $line, 2); + if ($username === $fileUser && $password === $filePass) { + $response['authenticated'] = true; + break; + } + } + return $response['authenticated']; } @@ -49,7 +53,7 @@ foreach ($files as $file) { $fileDate = date(DATE_TIME_FORMAT, filemtime($filePath)); $uploadDate = date(DATE_TIME_FORMAT, filectime($filePath)); $fileSizeFormatted = ($fileSizeBytes >= 1048576) ? sprintf("%.1f MB (%s bytes)", $fileSizeBytes / 1048576, number_format($fileSizeBytes)) : sprintf("%s bytes", number_format($fileSizeBytes)); - $fileUrl = BASE_URL . urlencode($file); + $fileUrl = BASE_URL . rawurlencode($file); $fileList[] = [ 'name' => htmlspecialchars($file, ENT_QUOTES, 'UTF-8'), 'size' => $fileSizeFormatted, diff --git a/getUploadSize.php b/getUploadSize.php new file mode 100644 index 0000000..19fb0d5 --- /dev/null +++ b/getUploadSize.php @@ -0,0 +1,15 @@ +isFile()) { + $size += $file->getSize(); + } + } + return $size; +} + +echo getDirectorySize(UPLOAD_DIR); +?> diff --git a/styles.css b/styles.css new file mode 100644 index 0000000..9200cf7 --- /dev/null +++ b/styles.css @@ -0,0 +1,84 @@ +.container { + margin-top: 10px; +} +.btn-upload { + background-color: #007bff; + color: white; + border-radius: 5px; +} +.btn-upload:disabled { + background-color: gray; +} +.btn-choose-file { + background-color: #6c757d; + color: white; + border-radius: 5px; +} +.file-list { + margin-top: 10px; +} +.progress { + margin-top: 10px; + height: 20px; /* Narrow progress bar */ + width: 100%; +} +.progress-bar { + height: 100%; /* Fill the entire height */ +} +table { + width: 100%; + border-collapse: collapse; +} +table, th, td { + border: 1px solid black; +} +th, td { + padding: 10px; + text-align: left; +} +tr:nth-child(even) { + background-color: #f2f2f2; +} +h2 { + font-size: 1.5em; /* Smaller font size */ +} +.form-group { + margin-bottom: 5px; /* Reduce vertical space between form groups */ +} +label { + font-size: 0.9em; /* Smaller font size */ +} +.btn { + font-size: 0.9em; /* Smaller font size for buttons */ +} +.align-items-center { + display: flex; + align-items: center; +} +.table th button { + background: none; + border: none; + color: inherit; + cursor: pointer; + padding: 0; +} +#loginForm, #uploadForm { + display: none; +} +.form-row { + align-items: flex-start; /* Align items by top */ +} +.full-width { + width: 100%; +} +.btn-delete { + background-color: #dc3545; + color: white; + border: none; + padding: 5px 10px; + cursor: pointer; + border-radius: 5px; +} +.btn-delete:hover { + background-color: #c82333; +} diff --git a/upload.js b/upload.js index 671f21e..6108c91 100644 --- a/upload.js +++ b/upload.js @@ -51,7 +51,7 @@ document.getElementById('uploadFileForm').addEventListener('submit', async funct const endTime = Date.now(); const uploadTime = (endTime - startTime) / 1000; const fileSize = fileInput.files[0].size; - const uploadRate = (fileSize / 1024 / uploadTime).toFixed(2); + const uploadRate = (fileSize / 1024 / uploadTime).toFixed(0); if (xhr.status === 200) { statusMessage.innerHTML = `File ${fileInput.files[0].name} successfully uploaded. Upload time: ${uploadTime.toFixed(2)} seconds. Upload rate: ${uploadRate} KBps.`; @@ -73,32 +73,10 @@ document.getElementById('uploadFileForm').addEventListener('submit', async funct } }); -async function loadFileList() { - try { - const { username, password } = authCredentials; - console.log('Loading file list with credentials:', { username, password }); // Debugging - const response = await fetch('file_list.php', { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - }, - body: JSON.stringify({ username, password }), - }); - if (!response.ok) { - throw new Error(`HTTP error! status: ${response.status}`); - } - const fileList = await response.json(); - console.log('File list loaded:', fileList); // Debugging: Log the file list to the console - displayFileList(fileList); - } catch (error) { - console.error('Error loading file list:', error); // Debugging: Log any errors to the console - } -} - async function deleteFile(fileName) { const { username, password } = authCredentials; try { - const response = await fetch('file_list.php', { + const response = await fetch('getFileList.php', { method: 'POST', headers: { 'Content-Type': 'application/json', diff --git a/upload.php b/upload.php index ff013ac..f37f599 100644 --- a/upload.php +++ b/upload.php @@ -2,6 +2,32 @@ require_once 'config.php'; require_once 'auth.php'; +// Function to convert size to bytes +function convertToBytes($size) { + $number = substr($size, 0, -1); + switch (strtoupper(substr($size, -1))) { + case 'G': + return $number * 1024 * 1024 * 1024; + case 'M': + return $number * 1024 * 1024; + case 'K': + return $number * 1024; + default: + return $size; + } +} + +// Function to get the total size of files in the directory +function getDirectorySize($dir) { + $size = 0; + foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir)) as $file) { + if ($file->isFile()) { + $size += $file->getSize(); + } + } + return $size; +} + // Check if the form was submitted if ($_SERVER['REQUEST_METHOD'] == 'POST') { // Get the username and password @@ -16,22 +42,34 @@ if ($_SERVER['REQUEST_METHOD'] == 'POST') { $uploadFile = UPLOAD_DIR . basename($_FILES['file']['name']); $tmpFile = $_FILES['file']['tmp_name']; - // Move the uploaded file to the specified directory - if (move_uploaded_file($tmpFile, $uploadFile)) { - // Preserve the original file modification time - touch($uploadFile, $fileDateTime); - echo "File is valid, and was successfully uploaded.\n"; + // Get the total upload limit from config and convert to bytes + $totalUploadLimit = convertToBytes(TOTAL_UPLOAD_SIZE); + // Get the current size of the upload directory + $currentDirSize = getDirectorySize(UPLOAD_DIR); + // Get the size of the new file + $fileSize = $_FILES['file']['size']; + + // Check if adding the new file exceeds the total upload limit + if (($currentDirSize + $fileSize) > $totalUploadLimit) { + echo "Upload denied. Total upload limit exceeded."; } else { - echo "File upload failed! "; - print_r(error_get_last()); - } + // Move the uploaded file to the specified directory + if (move_uploaded_file($tmpFile, $uploadFile)) { + // Preserve the original file modification time + touch($uploadFile, $fileDateTime); + echo "File is valid, and was successfully uploaded."; + } else { + echo "File upload failed! "; + print_r(error_get_last()); + } + } } else { - echo "No file uploaded or file upload error!\n"; + echo "No file uploaded or file upload error!"; echo "Error code: " . $_FILES['file']['error']; } } else { - echo "Invalid username or password!\n"; + echo "Invalid username or password!"; } } else { - echo "Invalid request method!\n"; + echo "Invalid request method!"; } diff --git a/users.txt b/users.txt new file mode 100644 index 0000000..2bd4d1b --- /dev/null +++ b/users.txt @@ -0,0 +1,2 @@ +uploader:uploader +