added new/changed files

This commit is contained in:
Sergey Svinolobov
2024-06-26 00:47:18 -04:00
parent ad41b84496
commit 3814366b39
13 changed files with 335 additions and 89 deletions

4
.htaccess Normal file
View File

@@ -0,0 +1,4 @@
<Files "users.txt">
Order Allow,Deny
Deny from all
</Files>

25
app.py
View File

@@ -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)

View File

@@ -1,25 +1,27 @@
<?php
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
session_start();
$data = json_decode(file_get_contents('php://input'), true);
$username = $data['username'];
$password = $data['password'];
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'];
}

77
checkUploadLimit.js Normal file
View File

@@ -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;

44
checkUploadLimit.php Normal file
View File

@@ -0,0 +1,44 @@
<?php
require_once 'config.php';
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 getDirectorySize($dir) {
$size = 0;
foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir)) as $file) {
if ($file->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);
?>

View File

@@ -1,8 +1,9 @@
<?php
// config.php
define('UPLOAD_DIR', '/var/www/html/upload/');
define('BASE_URL', 'https://yoursite.com/upload/');
define('BASE_URL', 'https://yourwebsite.com/upload/');
define('TIMEZONE', 'America/New_York');
define('DATE_TIME_FORMAT', 'm/d/y H:i');
define('TOTAL_UPLOAD_SIZE', '20G');
date_default_timezone_set(TIMEZONE);
?>

View File

@@ -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 = '';

View File

@@ -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,

15
getUploadSize.php Normal file
View File

@@ -0,0 +1,15 @@
<?php
require_once 'config.php';
function getDirectorySize($dir) {
$size = 0;
foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir)) as $file) {
if ($file->isFile()) {
$size += $file->getSize();
}
}
return $size;
}
echo getDirectorySize(UPLOAD_DIR);
?>

84
styles.css Normal file
View File

@@ -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;
}

View File

@@ -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 <b>${fileInput.files[0].name}</b> successfully uploaded. Upload time: <b>${uploadTime.toFixed(2)}</b> seconds. Upload rate: <b>${uploadRate}</b> 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',

View File

@@ -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!";
}

2
users.txt Normal file
View File

@@ -0,0 +1,2 @@
uploader:uploader