working upload functionality

This commit is contained in:
0ceanSlim 2024-04-16 10:05:34 -04:00
parent 514491ea62
commit 85a689fb52
7 changed files with 1025 additions and 148 deletions

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

View File

@ -2,11 +2,11 @@
import { NDKNip07Signer } from "@nostr-dev-kit/ndk";
import NDK from "@nostr-dev-kit/ndk";
document.querySelector('button').addEventListener('click', login);
document.querySelector("button").addEventListener("click", login);
async function fetchUserProfile(npub, ndk) {
try {
console.log('Fetching user profile for npub:', npub);
console.log("Fetching user profile for npub:", npub);
const user = ndk.getUser({ npub });
await user.fetchProfile();
console.log("User profile:", user.profile);
@ -16,10 +16,9 @@ async function fetchUserProfile(npub, ndk) {
throw error;
}
}
const relays = (["wss://nostr.happytavern.co"])
const relays = ["wss://nostr.happytavern.co"];
const ndk = new NDK({ explicitRelayUrls: relays });
async function login() {
try {
const signer = new NDKNip07Signer();
@ -40,39 +39,88 @@ async function login() {
console.log("User's nip05:", nip05);
// Check if user's public key exists in the nostr.json
const nostrJsonResponse = await fetch('/.well-known/nostr.json');
const nostrJsonResponse = await fetch("/.well-known/nostr.json");
if (!nostrJsonResponse.ok) {
throw new Error('Failed to fetch nostr.json: ' + nostrJsonResponse.statusText);
throw new Error(
"Failed to fetch nostr.json: " + nostrJsonResponse.statusText
);
}
const nostrJson = await nostrJsonResponse.json();
console.log("nostrJson object:", nostrJson);
// Extract the username from the NIP-05 identifier
const nip05Username = nip05.split('@')[0];
const nip05Username = nip05.split("@")[0];
//TODO AUTHENTICATE USER AND SEND TO UPLOAD//
//PROBABLY NEED SESSION MANAGEMENT TO ENSURE SECURE UPLOAD
//AND TO REMEMBER LOGIN
if (nostrJson.names[nip05Username] === user.pubkey) {
// User exists in nostr.json, proceed with further authentication or actions
console.log('User authenticated successfully.');
console.log("User authenticated successfully.");
localStorage.setItem("nip05Username", nip05Username);
// Redirect or show UI for file upload
showFileUploadUI();
} else {
console.log('User not found in the authentication database.');
alert('User not found in the authentication database.');
console.log("User not found in the authentication database.");
alert("User not found in the authentication database.");
}
} else {
console.log('User information not available from signer.');
console.log("User information not available from signer.");
}
} catch (error) {
console.error('Error during authentication:', error);
alert('Error during authentication: ' + error.message);
console.error("Error during authentication:", error);
alert("Error during authentication: " + error.message);
}
}
function showFileUploadUI() {
// Show UI for file upload
console.log('Show file upload UI...');
// Implement UI logic for file upload
}
// Clear any existing content
document.body.innerHTML = "";
// Create file input element
const fileInput = document.createElement("input");
fileInput.type = "file";
fileInput.addEventListener("change", handleFileSelect);
// Create submit button
const submitButton = document.createElement("button");
submitButton.textContent = "Upload";
submitButton.addEventListener("click", handleUpload);
// Append elements to the body
document.body.appendChild(fileInput);
document.body.appendChild(submitButton);
}
function handleFileSelect(event) {
const selectedFile = event.target.files[0];
console.log("Selected file:", selectedFile);
}
const serverUrl = "http://localhost:3000"; // Adjust the port as needed
async function handleUpload() {
const fileInput = document.querySelector('input[type="file"]');
const selectedFile = fileInput.files[0];
const nip05Username = localStorage.getItem("nip05Username"); // Assuming you have a function to get nip05Username
const formData = new FormData();
formData.append("file", selectedFile);
try {
const response = await fetch(
`${serverUrl}/upload?nip05Username=${nip05Username}`,
{
method: "POST",
body: formData,
}
);
if (response.ok) {
console.log("File uploaded successfully");
// Handle success
} else {
throw new Error("Failed to upload file");
}
} catch (error) {
console.error("Error uploading file:", error);
// Handle error
}
}

947
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -10,8 +10,10 @@
"license": "MIT",
"dependencies": {
"@nostr-dev-kit/ndk": "^2.6.1",
"bech32": "^2.0.0",
"bitcoinjs-lib": "^6.1.5",
"cors": "^2.8.5",
"express": "^4.19.2",
"multer": "^1.4.5-lts.1",
"path": "^0.12.7",
"vite": "^5.2.7"
}
}

View File

@ -12,5 +12,30 @@ install dependencies:
run the dev server:
`vite`
go to http://localhost:5173
check out the console (right click inspect)
listen for uploads (run backend server)
`node server`
go to http://localhost:5173
check out the console (right click inspect)
TODO:
Check for security make sure I can't get around it some easy way at least.
new npub with proper nip05 and username access?
create a setup that runs both frontend and backend code and make a config file
for any configs for the user
set up create path if it doesn't exist for a new user.
config for max file size and default storage limit for a given iser
can make a exceptions later to allow more storage for a user based on criterea
the .well-known and .nip05Storage are for testing purposed right now. they will be removed later.
redo readme
get rid of cors errors?
make favicon
test on my site
release

29
server.js Normal file
View File

@ -0,0 +1,29 @@
const express = require("express");
const multer = require("multer");
const path = require("path");
const app = express();
// Set up multer for handling file uploads
const storage = multer.diskStorage({
destination: function (req, file, cb) {
const nip05Username = req.query.nip05Username; // Extract nip05Username from query params
const uploadPath = path.join(__dirname, ".nip05Storage", nip05Username);
cb(null, uploadPath);
},
filename: function (req, file, cb) {
cb(null, file.originalname);
},
});
const upload = multer({ storage: storage });
app.listen(3000, () => {
console.log("Server is running on port 3000");
});
app.post("/upload", upload.single("file"), (req, res) => {
// The file has been uploaded to the destination folder
// Respond with success status
res.sendStatus(200);
});

View File

@ -1,74 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>File Upload</title>
</head>
<body>
<h1>File Upload</h1>
<form id="uploadForm" enctype="multipart/form-data">
<input type="file" name="file" multiple>
<button type="submit">Upload</button>
</form>
<script>
async function checkPermissions(npub) {
try {
const response = await fetch('https://happytaver.co/.well-known/nostr.json');
const data = await response.json();
return data.hasOwnProperty(npub);
} catch (error) {
console.error('Error checking permissions:', error);
return false;
}
}
document.getElementById('uploadForm').addEventListener('submit', async (event) => {
event.preventDefault();
const fileInput = document.querySelector('input[type="file"]');
const files = fileInput.files;
if (files.length === 0) {
alert('Please select a file to upload.');
return;
}
const npub = localStorage.getItem('npub'); // Assuming npub is stored in localStorage
if (!npub) {
alert('User not authenticated.');
return;
}
const hasPermission = await checkPermissions(npub);
if (!hasPermission) {
alert('User does not have permission to upload.');
return;
}
// Proceed with file upload
const formData = new FormData();
for (const file of files) {
formData.append('files', file);
}
try {
const uploadResponse = await fetch('https://your-upload-endpoint.com/upload', {
method: 'POST',
body: formData
});
const uploadData = await uploadResponse.json();
console.log('Upload successful:', uploadData);
alert('Files uploaded successfully.');
} catch (error) {
console.error('Error uploading files:', error);
alert('Error occurred during file upload.');
}
});
</script>
</body>
</html>