From cfccc24888605b17d6e571b16e675f37f4ba09ac Mon Sep 17 00:00:00 2001 From: unknown Date: Wed, 16 Oct 2024 19:56:16 +0200 Subject: [PATCH] bug fix --- .env.example => packages/svelte/.env.example | 0 packages/svelte/gun.config.js | 7 -- packages/svelte/gun.config.ts | 9 +++ packages/svelte/package.json | 2 +- .../gun/account/AccountAvatar.svelte | 43 +++++++---- .../gun/account/AccountProfile.svelte | 16 +++- packages/svelte/src/lib/gun/account.ts | 77 ------------------- packages/svelte/src/lib/gun/auth.ts | 44 ++++++++--- packages/svelte/src/lib/gun/avatar.ts | 40 +++++++--- packages/svelte/src/lib/gun/user.ts | 2 +- packages/svelte/src/routes/auth/+page.svelte | 54 ++++++++----- .../svelte/src/routes/inspect/+page.svelte | 3 +- yarn.lock | 12 ++- 13 files changed, 158 insertions(+), 151 deletions(-) rename .env.example => packages/svelte/.env.example (100%) delete mode 100644 packages/svelte/gun.config.js create mode 100644 packages/svelte/gun.config.ts diff --git a/.env.example b/packages/svelte/.env.example similarity index 100% rename from .env.example rename to packages/svelte/.env.example diff --git a/packages/svelte/gun.config.js b/packages/svelte/gun.config.js deleted file mode 100644 index bc58039..0000000 --- a/packages/svelte/gun.config.js +++ /dev/null @@ -1,7 +0,0 @@ -//export const peers = ["https://gun-relay.scobrudot.dev/gun"]; -import env from "dotenv"; - -env.config(); - -export const peers = ["https://peer.wallie.io/gun"]; -export const validToken = process.env.VALID_TOKEN; diff --git a/packages/svelte/gun.config.ts b/packages/svelte/gun.config.ts new file mode 100644 index 0000000..77ef733 --- /dev/null +++ b/packages/svelte/gun.config.ts @@ -0,0 +1,9 @@ +export const peers = ["https://gun-relay.scobrudot.dev/gun", "https://peer.wallie.io/gun"]; + +import env from "dotenv"; + +const { VALID_TOKEN } = env as { + VALID_TOKEN?: string; +}; + +export const validToken = VALID_TOKEN; diff --git a/packages/svelte/package.json b/packages/svelte/package.json index 63d80c7..8944559 100644 --- a/packages/svelte/package.json +++ b/packages/svelte/package.json @@ -70,7 +70,7 @@ "express-rate-limit": "^7.4.0", "gun": "^0.2020.1240", "gun-avatar": "^1.9.4", - "gun-eth": "^1.2.13", + "gun-eth": "^1.2.14", "ip": "^2.0.1", "js-sha256": "^0.11.0", "js-sha3": "^0.9.3", diff --git a/packages/svelte/src/lib/components/gun/account/AccountAvatar.svelte b/packages/svelte/src/lib/components/gun/account/AccountAvatar.svelte index fbabee2..6dc4fa7 100644 --- a/packages/svelte/src/lib/components/gun/account/AccountAvatar.svelte +++ b/packages/svelte/src/lib/components/gun/account/AccountAvatar.svelte @@ -2,51 +2,55 @@ import { useAvatar } from '$lib/gun/avatar'; import { useUser } from '$lib/gun/user'; import { onMount, createEventDispatcher } from 'svelte'; - const dispatch = createEventDispatcher(); const { user } = useUser(); - export let pub: string | undefined = undefined; export let size: number = 96; export let border: number = 2; - let isOwnAvatar = false; let fileInput: HTMLInputElement; let avatarLoaded = false; - $: ({ avatar, blink, uploadAvatar, uploadStatus } = useAvatar(pub || $user?.pub, size)); + let { avatar: avatarStore, blink, uploadAvatar, uploadStatus, updateAvatar } = useAvatar($user.pub, size); + $: console.log("Avatar nel componente:", $avatarStore); onMount(() => { - if (!pub && $user?.pub) { - pub = $user.pub; - } - isOwnAvatar = $user.pub === pub; - console.log("isOwnAvatar:", isOwnAvatar, "$user.pub:", $user.pub, "pub:", pub); + updateAvatar(); }); async function handleFileChange(event: Event) { const file = (event.target as HTMLInputElement).files?.[0]; - if (file) await uploadAvatar(file); + if (file) { + await uploadAvatar(file); + updateAvatar(); + } } function onAvatarLoad() { avatarLoaded = true; dispatch('load'); } + + function onAvatarError() { + avatarLoaded = true; + updateAvatar(); + dispatch('load'); + }
- {#if pub || $user?.pub} + {#if $user.pub} Avatar - {#if isOwnAvatar && avatarLoaded} + {#if avatarLoaded}
\ No newline at end of file + diff --git a/packages/svelte/src/lib/components/gun/account/AccountProfile.svelte b/packages/svelte/src/lib/components/gun/account/AccountProfile.svelte index 1beaf89..93ea0cc 100644 --- a/packages/svelte/src/lib/components/gun/account/AccountProfile.svelte +++ b/packages/svelte/src/lib/components/gun/account/AccountProfile.svelte @@ -7,12 +7,22 @@ let pub : string | undefined ; let { user } = useUser(); - let { account } = useAccount(pub || $user?.pub); + console.log("user pub", $user); + let { account } = useAccount($user?.pub); $: globalAccount = $account; - $: lastPulse = globalAccount?.pulse; + onMount(() => { + if (!pub && $user?.pub) { + pub = $user.pub; + } + }); + + $: pub = $user?.pub; + + + if (globalAccount && globalAccount.pulse !== lastPulse) { lastPulse = globalAccount.pulse; @@ -42,7 +52,7 @@

Account Information

- + {#if globalAccount} {#each accountFields as { key, label }}
diff --git a/packages/svelte/src/lib/gun/account.ts b/packages/svelte/src/lib/gun/account.ts index 4f1d4ce..f80249d 100644 --- a/packages/svelte/src/lib/gun/account.ts +++ b/packages/svelte/src/lib/gun/account.ts @@ -125,80 +125,3 @@ export async function setPetname(pub: string, name: string): Promise { const enc = await get(user).encrypt(name); gun.user().get("petnames").get(pub).put(enc); } - -export function useAvatar(pub: string, size: number) { - const gun = useGun(); - const { user } = useUser(); - const avatar = writable(""); - const blink = writable(false); - const uploadStatus = writable(""); - - const updateAvatar = () => { - console.log("Updating avatar for pub:", pub); - gun - .user(pub) - .get("avatar") - .once(data => { - console.log("Avatar data:", data); - if (data) { - avatar.set(data); - } else { - avatar.set(`https://avatars.dicebear.com/api/identicon/${pub}.svg?size=${size}`); - } - }); - }; - - updateAvatar(); - - gun - .user(pub) - .get("pulse") - .on(() => { - blink.update(b => !b); - }); - - const uploadAvatar = async (file: File) => { - console.log("Starting avatar upload"); - uploadStatus.set("Iniziando il caricamento..."); - - const currentUser = get(user); - if (!currentUser || !currentUser.is || currentUser.pub !== pub) { - console.error("Utente non autenticato o non autorizzato"); - uploadStatus.set("Errore: Utente non autenticato o non autorizzato"); - return; - } - - try { - const reader = new FileReader(); - reader.onload = async e => { - const base64 = e.target?.result as string; - uploadStatus.set("Salvando avatar..."); - - gun - .user() - .get("avatar") - .put(base64, ack => { - if (ack.err) { - console.error("Errore nel salvare l'avatar:", ack.err); - uploadStatus.set("Errore nel salvare l'avatar"); - } else { - console.log("Avatar salvato con successo"); - uploadStatus.set("Avatar caricato con successo"); - updateAvatar(); - } - }); - }; - reader.readAsDataURL(file); - } catch (error) { - console.error("Errore durante il caricamento dell'avatar:", error); - uploadStatus.set("Errore durante il caricamento. Riprova."); - } - }; - - return { - avatar: derived(avatar, $a => $a), - blink: derived(blink, $b => $b), - uploadAvatar, - uploadStatus: derived(uploadStatus, $s => $s), - }; -} diff --git a/packages/svelte/src/lib/gun/auth.ts b/packages/svelte/src/lib/gun/auth.ts index 1a153c8..1136ba5 100644 --- a/packages/svelte/src/lib/gun/auth.ts +++ b/packages/svelte/src/lib/gun/auth.ts @@ -1,6 +1,5 @@ import "gun-eth"; import { getAccount } from "@wagmi/core"; -import { currentUser, gun } from "$lib/stores"; import { derived, get, writable } from "svelte/store"; import { notification } from "$lib/utils/scaffold-eth/notification"; import { wagmiConfig } from "$lib/wagmi"; @@ -8,7 +7,6 @@ import type { IGunUserInstance } from "gun/types"; import { auth, leave, useUser, isPair } from "./user"; import { useGun } from "./gun"; import SEA from "gun/sea"; -import { useAccount } from "./account"; const MESSAGE_TO_SIGN = "Accesso a GunDB con Ethereum"; export function initializeAuth() { @@ -19,14 +17,12 @@ export function initializeAuth() { if ("err" in ack) { console.error("Errore nel recupero della sessione:", ack.err); } else if (user.is && user.is.alias) { - currentUser.set(user.is.alias as string); await loadUserData(user); } }); gun.user().on("auth", async () => { console.log("Utente autenticato:", user.is.alias as string); - currentUser.set(user.is.alias as string); await loadUserData(user); }); @@ -35,23 +31,26 @@ export function initializeAuth() { async function loadUserData(user: IGunUserInstance) { console.log("Caricamento dati utente..."); - const gunInstance = get(gun); + const gunInstance = useGun(); const account = getAccount(wagmiConfig); if (user.is && user.is.alias) { const signature = await gunInstance.createSignature(MESSAGE_TO_SIGN); const userPair = await gunInstance.getAndDecryptPair(account.address, signature); console.log("Coppia utente:", userPair); - // Qui puoi aggiungere la logica per gestire i dati dell'utente } } export async function signIn(): Promise { console.log("Registrazione in corso..."); + const gunInstance = useGun(); const account = getAccount(wagmiConfig); const { user } = useUser(); + // check if pair exist on gun for this address + + try { if (!account.isConnected) { return "Per favore connetti il tuo portafoglio Ethereum"; @@ -63,15 +62,36 @@ export async function signIn(): Promise { return "Errore durante la firma del messaggio"; } - await gunInstance.createAndStoreEncryptedPair(account.address, signature); + // Verifica se esiste già un encrypted pair per questo utente + const existingPair = await gunInstance.get(`~${account.address}`).get("safe").get("enc").then(); + const remoteKeyPair = gunInstance.get("gun-eth").get("users").get(account.address).get("pair"); + + if (existingPair || remoteKeyPair) { + console.log("Encrypted pair esistente trovato. Esecuzione del login..."); + await gunInstance.get(`~${account.address}`).get("safe").get("enc").put(remoteKeyPair); + return login(signature); + } + + let pair = await gunInstance.createAndStoreEncryptedPair(account.address, signature); + console.log("Pair:", pair); return new Promise(resolve => { gunInstance.user().create(account.address, signature, async (ack: { ok: 0; pub: string } | { err: string }) => { if ("err" in ack) { - resolve("Errore durante la registrazione: " + ack.err); + resolve("Error during registration: " + ack.err); } else { await loadUserData(user); - currentUser.set(user.is.alias); + await auth(pair, async (ack: { err: string }) => { + console.log("Risposta di autenticazione:", ack); + if (ack.err) { + console.error("Errore di accesso: " + ack.err); + } else { + console.log("Accesso riuscito"); + const { user } = useUser(); + user.update(u => ({ ...u, auth: true, pub: gunInstance.user().is.alias })); + console.log("User:", get(user)); + } + }); resolve(null); } }); @@ -81,7 +101,7 @@ export async function signIn(): Promise { } } -export async function login(): Promise { +export async function login(sig?: string): Promise { const account = getAccount(wagmiConfig); if (!account.isConnected) { @@ -96,7 +116,7 @@ export async function login(): Promise { return "Nessun account Ethereum connesso"; } - const signature = await gunInstance.createSignature(MESSAGE_TO_SIGN); + const signature = sig ? sig : await gunInstance.createSignature(MESSAGE_TO_SIGN); if (!signature) { return "Errore durante la firma del messaggio"; } @@ -115,7 +135,7 @@ export async function login(): Promise { } else { console.log("Accesso riuscito"); const { user } = useUser(); - user.update(u => ({ ...u, auth: true })); + user.update(u => ({ ...u, auth: true, pub: gunInstance.user().is.alias })); console.log("User:", get(user)); } }); diff --git a/packages/svelte/src/lib/gun/avatar.ts b/packages/svelte/src/lib/gun/avatar.ts index c603695..ce39d3f 100644 --- a/packages/svelte/src/lib/gun/avatar.ts +++ b/packages/svelte/src/lib/gun/avatar.ts @@ -2,6 +2,7 @@ import { derived, writable, get } from "svelte/store"; import { useGun } from "./gun"; import { useUser } from "./user"; import SEA from "gun/sea"; +import { gunAvatar } from "gun-avatar" export function useAvatar(pub: string, size: number) { const gun = useGun(); @@ -12,10 +13,15 @@ export function useAvatar(pub: string, size: number) { const updateAvatar = () => { console.log("Updating avatar for pub:", pub); + if (!pub) { + console.log("No pub provided, setting default avatar"); + setDefaultAvatar(); + return; + } gun .user(pub) .get("avatar") - .once(data => { + .once((data: string) => { console.log("Avatar data:", data); if (data) { if (typeof data === "string" && data.startsWith("#")) { @@ -23,7 +29,7 @@ export function useAvatar(pub: string, size: number) { gun .get("#") .get(data.slice(1)) - .once(media => { + .once((media: string) => { console.log("Retrieved media:", media); if (media) { try { @@ -31,24 +37,28 @@ export function useAvatar(pub: string, size: number) { avatar.set(`data:${mediaObj.type};base64,${mediaObj.b64}`); } catch (error) { console.error("Error parsing media:", error); - avatar.set(`https://avatars.dicebear.com/api/identicon/${pub}.svg?size=${size}`); + setDefaultAvatar(); } } else { - avatar.set(`https://avatars.dicebear.com/api/identicon/${pub}.svg?size=${size}`); + setDefaultAvatar(); } }); } else if (typeof data === "string" && data.startsWith("data:")) { // L'avatar è già in formato base64 avatar.set(data); } else { - avatar.set(`https://avatars.dicebear.com/api/identicon/${pub}.svg?size=${size}`); + setDefaultAvatar(); } } else { - avatar.set(`https://avatars.dicebear.com/api/identicon/${pub}.svg?size=${size}`); + setDefaultAvatar(); } }); }; + const setDefaultAvatar = () => { + avatar.set(gunAvatar({ pub, size })); + }; + gun .user(pub) .get("pulse") @@ -85,7 +95,7 @@ export function useAvatar(pub: string, size: number) { gun .get("#") .get(mediaID) - .put(media, ack => { + .put(media, (ack: { err: any; }) => { if (ack.err) { console.error("Errore nel salvare il media:", ack.err); reject(ack.err); @@ -99,9 +109,9 @@ export function useAvatar(pub: string, size: number) { // Salva il riferimento all'avatar nello spazio utente await new Promise((resolve, reject) => { gun - .user() + .user(pub) .get("avatar") - .put("#" + mediaID, ack => { + .put("#" + mediaID, (ack: { err: any; }) => { if (ack.err) { console.error("Errore nel salvare il riferimento avatar:", ack.err); reject(ack.err); @@ -121,12 +131,22 @@ export function useAvatar(pub: string, size: number) { console.error("Errore durante il caricamento dell'avatar:", error); uploadStatus.set("Errore durante il caricamento. Riprova."); } + + // Dopo aver completato il caricamento, aggiorna immediatamente l'avatar + updateAvatar(); }; + // Chiama updateAvatar all'inizializzazione + updateAvatar(); + return { - avatar: derived(avatar, $a => $a), + avatar: derived(avatar, $a => { + console.log("Avatar value:", $a); + return $a; + }), blink: derived(blink, $b => $b), uploadAvatar, uploadStatus: derived(uploadStatus, $s => $s), + updateAvatar }; } diff --git a/packages/svelte/src/lib/gun/user.ts b/packages/svelte/src/lib/gun/user.ts index bc39ed0..fe11597 100644 --- a/packages/svelte/src/lib/gun/user.ts +++ b/packages/svelte/src/lib/gun/user.ts @@ -147,7 +147,7 @@ export async function auth(pair: any, cb = (pair: any) => {}) { cb(ack); } else { const { user } = useUser(); - user.update(u => ({ ...u, auth: true })); + user.update(u => ({ ...u, auth: true, pub: gun.user().is.alias })); console.log("Successo autenticazione"); cb(ack); } diff --git a/packages/svelte/src/routes/auth/+page.svelte b/packages/svelte/src/routes/auth/+page.svelte index 4a863c7..8fa7779 100644 --- a/packages/svelte/src/routes/auth/+page.svelte +++ b/packages/svelte/src/routes/auth/+page.svelte @@ -7,9 +7,11 @@ import { notification } from "$lib/utils/scaffold-eth/notification"; import { initializeAuth, signIn, login, logout } from "$lib/gun/auth"; import { useUser, loadUserProfile } from "$lib/gun/user"; + import { writable } from 'svelte/store'; import AccountProfile from "$lib/components/gun/account/AccountProfile.svelte"; import ProfileDisplay from "$lib/components/gun/profile/ProfileDisplay.svelte"; + import { useGun } from "$lib/gun/gun"; let errorMessage: string | null = null; let userPair: Record | null = null; @@ -18,12 +20,9 @@ let errorTimeoutId: number; - onMount(() => { - initializeAuth(); - return () => { - if (errorTimeoutId) clearTimeout(errorTimeoutId); - }; - }); + const userPairStore = writable(null); + + function setErrorMessage(message: string | null) { if (errorTimeoutId) clearTimeout(errorTimeoutId); @@ -37,10 +36,13 @@ async function handleSignIn() { const result = await signIn(); - if (result) { + if (result === "login") { + // Se signIn restituisce "login", significa che abbiamo trovato un encrypted pair esistente + handleLogin(); + } else if (result) { setErrorMessage(result); } else { - notification.success("Registration completed successfully!"); + notification.success("Registrazione completata con successo!"); loadUserProfile(); } } @@ -50,7 +52,7 @@ if (result) { setErrorMessage(result); } else { - notification.success("Login successful!"); + notification.success("Login effettuato con successo!"); loadUserProfile(); } } @@ -62,7 +64,7 @@ } async function handleViewPair() { - const gunInstance = get(gun); + const gunInstance = useGun(); const account = getAccount(wagmiConfig); if (!account.isConnected) { @@ -77,14 +79,24 @@ return; } - userPair = await gunInstance.getAndDecryptPair(account.address, signature); - if (!userPair) { + const pair = await gunInstance.getAndDecryptPair(account.address, signature); + + console.log("User Pair:", pair); + if (!pair) { setErrorMessage("Unable to retrieve user data"); + } else { + userPairStore.set(pair); } } catch (error) { setErrorMessage("Error retrieving pair: " + error.message); } } + + $effect(() => { + if (errorMessage) { + notification.error(errorMessage); + } + });
@@ -96,14 +108,14 @@ {#if $user?.auth === false}
- - + +
{:else}
-

Benvenuto, {$user?.profile?.name || $user?.pub}!

+

👋 Welcome, {$user?.profile?.name || $user?.pub}!

-
+
- {#if userPair && Object.keys(userPair).length > 0} + {#if $userPairStore}

User Pair

    - {#each Object.entries(userPair) as [key, value]} + {#each Object.entries($userPairStore) as [key, value]}
  • {key}: {JSON.stringify(value, null, 2)}
  • @@ -132,8 +144,8 @@
{/if}
- - + +
{/if} @@ -181,4 +193,4 @@
\ No newline at end of file + diff --git a/packages/svelte/src/routes/inspect/+page.svelte b/packages/svelte/src/routes/inspect/+page.svelte index 5c91f52..d24df8a 100644 --- a/packages/svelte/src/routes/inspect/+page.svelte +++ b/packages/svelte/src/routes/inspect/+page.svelte @@ -183,8 +183,9 @@ Current Relay: {$customRelay} diff --git a/yarn.lock b/yarn.lock index 8742a5a..cdd8fa2 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2387,7 +2387,7 @@ __metadata: express-rate-limit: ^7.4.0 gun: ^0.2020.1240 gun-avatar: ^1.9.4 - gun-eth: ^1.2.13 + gun-eth: ^1.2.14 ip: ^2.0.1 js-sha256: ^0.11.0 js-sha3: ^0.9.3 @@ -9382,6 +9382,16 @@ __metadata: languageName: node linkType: hard +"gun-eth@npm:^1.2.14": + version: 1.2.14 + resolution: "gun-eth@npm:1.2.14" + dependencies: + ethers: ^6.0.0 + gun: ^0.2020.1239 + checksum: 8c7eaa7526792f28f99fe7549e8d68a53ba5bc819ec88417a89c369725971c19f65e2d89b80edeb7253c78225be9e61e6b7fdf860eef2e83f9a0342c6bd36a2e + languageName: node + linkType: hard + "gun@npm:0.2020.1239": version: 0.2020.1239 resolution: "gun@npm:0.2020.1239"