nostrMediaUpload/index.js
2024-04-14 20:04:50 -04:00

72 lines
2.3 KiB
JavaScript

// Import the Nostr SDK package
import { NDKNip07Signer } from "@nostr-dev-kit/ndk";
import NDK from "@nostr-dev-kit/ndk";
document.querySelector('button').addEventListener('click', login);
async function fetchUserProfile(npub, ndk) {
try {
console.log('Fetching user profile for npub:', npub);
const user = ndk.getUser({ npub });
await user.fetchProfile();
console.log("User profile:", user.profile);
return user;
} catch (error) {
console.error("Error fetching user profile:", error);
throw error;
}
}
const relays = (["wss://nostr.happytavern.co"])
const ndk = new NDK({ explicitRelayUrls: relays });
async function login() {
try {
const signer = new NDKNip07Signer();
// Connect to the NDK
await ndk.connect();
// Wait for the user to be obtained from the signer
const user = await signer.user();
if (!!user.pubkey && user.npub) {
console.log("Permission granted to read their public key:", user.pubkey);
// Fetch user profile
const userProfile = await fetchUserProfile(user.npub, ndk);
const displayName = userProfile.profile.displayName;
console.log("User's display name:", displayName);
// Check if user's public key exists in the nostr.json
const nostrJsonResponse = await fetch('/.well-known/nostr.json');
if (!nostrJsonResponse.ok) {
throw new Error('Failed to fetch nostr.json: ' + nostrJsonResponse.statusText);
}
const nostrJson = await nostrJsonResponse.json();
console.log("nostrJson object:", nostrJson);
if (nostrJson.names[displayName] === user.pubkey) {
// User exists in nostr.json, proceed with further authentication or actions
console.log('User authenticated successfully.');
// 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.');
}
} else {
console.log('User information not available from signer.');
}
} catch (error) {
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
}