Skip to content

Commit

Permalink
bug fix
Browse files Browse the repository at this point in the history
  • Loading branch information
scobru committed Oct 16, 2024
1 parent 3f1ab1b commit cfccc24
Show file tree
Hide file tree
Showing 13 changed files with 158 additions and 151 deletions.
File renamed without changes.
7 changes: 0 additions & 7 deletions packages/svelte/gun.config.js

This file was deleted.

9 changes: 9 additions & 0 deletions packages/svelte/gun.config.ts
Original file line number Diff line number Diff line change
@@ -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;
2 changes: 1 addition & 1 deletion packages/svelte/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
43 changes: 26 additions & 17 deletions packages/svelte/src/lib/components/gun/account/AccountAvatar.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -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');
}
</script>

<div class="flex flex-col items-center justify-center relative w-fit">
{#if pub || $user?.pub}
{#if $user.pub}
<img
class="border rounded-full overflow-hidden transition duration-500 ease-out"
style="border-color: {$blink ? 'accent' : 'transparent'}; border-width: {border}px;"
width={size}
height={size}
src={$avatar}
src={$avatarStore}
alt="Avatar"
on:load={onAvatarLoad}
on:error={onAvatarError}
/>
{#if isOwnAvatar && avatarLoaded}
{#if avatarLoaded}
<button
class="absolute bottom-0 right-0 bg-accent text-white rounded-full p-1 hover:bg-accent/80"
on:click={() => fileInput.click()}
Expand All @@ -65,9 +69,14 @@
{/if}
{/if}
{:else}
<div class="pb-2 px-1" style="font-size: {size}px;">
<div class="i-la-user"></div>
</div>
<img
class="border rounded-full overflow-hidden"
style="border-width: {border}px;"
width={size}
height={size}
src={`https://avatars.dicebear.com/api/identicon/${$user.pub}.svg?size=${size}`}
alt="Default Avatar"
/>
{/if}
<slot></slot>
</div>
</div>
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -42,7 +52,7 @@
<div class="card w-90 bg-ableton-light-blue text-black rounded-none p-4 font-sans">
<div class="card-body">
<h2 class="card-title text-black font-medium text-2xl">Account Information</h2>
<AccountAvatar pub={pub || $user?.pub} />
<AccountAvatar pub={$user?.pub} />
{#if globalAccount}
{#each accountFields as { key, label }}
<div class="form-control gap-2">
Expand Down
77 changes: 0 additions & 77 deletions packages/svelte/src/lib/gun/account.ts
Original file line number Diff line number Diff line change
Expand Up @@ -125,80 +125,3 @@ export async function setPetname(pub: string, name: string): Promise<void> {
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),
};
}
44 changes: 32 additions & 12 deletions packages/svelte/src/lib/gun/auth.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,12 @@
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";
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() {
Expand All @@ -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);
});

Expand All @@ -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<string | null> {
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";
Expand All @@ -63,15 +62,36 @@ export async function signIn(): Promise<string | null> {
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);
}
});
Expand All @@ -81,7 +101,7 @@ export async function signIn(): Promise<string | null> {
}
}

export async function login(): Promise<string | null> {
export async function login(sig?: string): Promise<string | null> {
const account = getAccount(wagmiConfig);

if (!account.isConnected) {
Expand All @@ -96,7 +116,7 @@ export async function login(): Promise<string | null> {
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";
}
Expand All @@ -115,7 +135,7 @@ export async function login(): Promise<string | null> {
} 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));
}
});
Expand Down
Loading

0 comments on commit cfccc24

Please sign in to comment.