source: frontend/web3-eDnevnik_Frontend/src/components/RoditelSettings/RoditelSettings.jsx@ 81cdf2d

Last change on this file since 81cdf2d was 81cdf2d, checked in by Nikola Janev <nikolajanev57@…>, 9 days ago

initial commit

  • Property mode set to 100644
File size: 4.4 KB
Line 
1import { useState, useEffect } from "react";
2import NavbarRoditel from "../NavbarRoditel/NavbarRoditel.jsx";
3import styles from "./RoditelSettingsStyles.module.css";
4import { ethers } from "ethers";
5import { data } from "react-router-dom";
6import axios from "axios";
7import { useAuth } from "../../contexts/AuthContext.jsx";
8
9const RoditelSettings = () => {
10 const {
11 walletAddress: backendWalletAddress,
12 setBackendWalletAddress,
13 fetchSavedWallet,
14 } = useAuth();
15 const [savedWallet, setSavedWallet] = useState(null);
16 const [loading, setLoading] = useState(false);
17 const [roditelId, setRoditelId] = useState(null);
18
19 const connectWallet = async () => {
20 if (!window.ethereum) {
21 alert("Ве молиме инсталирајте MetaMask!");
22 return;
23 }
24
25 try {
26 setLoading(true);
27
28 //proverka dali e sepolia mreza
29 const chainId = await window.ethereum.request({ method: "eth_chainId" });
30 if (chainId !== "0xaa36a7") {
31 alert("Ве молиме префрлете се на Sepolia мрежата!");
32 setLoading(false);
33 return;
34 }
35
36 // zemanje na adresa
37 const accounts = await window.ethereum.request({
38 method: "eth_requestAccounts",
39 });
40 const address = accounts[0];
41
42 //zemanje na nonce od backend
43 const nonceRes = await fetch(
44 `http://localhost:8080/metamuskAuth/nonce?address=${address}`,
45 { credentials: "include" }
46 );
47
48 if (!nonceRes.ok) {
49 const errorText = await nonceRes.text();
50 throw new Error(
51 `Проблем со серверот (${nonceRes.status}): ${errorText}`
52 );
53 }
54
55 const { nonce } = await nonceRes.json();
56
57 // potpisuvanje na transakcijata za povrzuvanje na wallet
58 const provider = new ethers.BrowserProvider(window.ethereum);
59 const signer = await provider.getSigner();
60 const signature = await signer.signMessage(nonce);
61
62 // linkuvanje so backend za zapisuvanje
63 const res = await fetch(
64 "http://localhost:8080/metamuskAuth/link-wallet-roditel",
65 {
66 method: "POST",
67 headers: { "Content-Type": "application/json" },
68 body: JSON.stringify({
69 address: address.toLowerCase(),
70 signature,
71 }),
72 credentials: "include",
73 }
74 );
75
76 const data = await res.json();
77
78 if (!res.ok) {
79 throw new Error(data.message || "Неуспешно поврзување на паричникот.");
80 }
81
82 setBackendWalletAddress(address);
83 setSavedWallet(null);
84 alert("Паричникот е успешно поврзан!");
85 } catch (err) {
86 console.error("MetaMask Error:", err);
87 alert(err.message || "Се случи неочекувана грешка.");
88 } finally {
89 setLoading(false);
90 }
91 };
92
93 const handleDisconnectWallet = async () => {
94 try {
95 const response = await axios.post(
96 "http://localhost:8080/metamuskAuth/unlink-wallet",
97 {},
98 {
99 withCredentials: true,
100 }
101 );
102 if (response.status === 200) {
103 setBackendWalletAddress(null);
104 setSavedWallet(null);
105 }
106 } catch (err) {
107 console.log(`Error while disconnectiong a wallet ${err}`);
108 }
109 };
110
111 return (
112 <>
113 <div className={styles.mainContainer}>
114 <NavbarRoditel />
115 <div className={styles.contentCard}>
116 <h1 className={styles.heading}>Подесувања за профилот</h1>
117
118 <div className={styles.metamuskSettings}>
119 <div className={styles.cryptoHeader}>
120 <h2>Опции за metamusk</h2>
121 <p>
122 Вашата Metamusk адреса:{" "}
123 {backendWalletAddress ? backendWalletAddress : "/"}
124 </p>
125 </div>
126
127 <div className={styles.actionArea}>
128 {!backendWalletAddress ? (
129 <button
130 className={styles.connectBtn}
131 onClick={connectWallet}
132 disabled={loading}
133 >
134 {loading ? "Поврзување..." : "Поврзете MetaMask wallet"}
135 </button>
136 ) : (
137 <button onClick={handleDisconnectWallet}>Disconnect</button>
138 )}
139 </div>
140 </div>
141 </div>
142 </div>
143 </>
144 );
145};
146
147export default RoditelSettings;
Note: See TracBrowser for help on using the repository browser.