-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
149 lines (123 loc) · 4.78 KB
/
Copy pathscript.js
File metadata and controls
149 lines (123 loc) · 4.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
document.addEventListener("DOMContentLoaded", () => {
// Selecting elements
const walletButton = document.getElementById("connect-wallet");
const disconnectButton = document.getElementById("disconnect-button");
const walletOptions = document.getElementById("wallet-options");
const registerButton = document.querySelector(".btn-register"); // Ensure class exists in HTML
let userWallet = null;
const TOKEN_KEY = "bimbfa_jwt_token"; // ✅ Unique key to avoid overwriting other tokens
// **🔹 Add Event Listeners First**
if (walletButton) {
walletButton.addEventListener("click", async () => {
if (!userWallet) {
await connectWallet();
}
});
}
if (disconnectButton) {
disconnectButton.addEventListener("click", () => {
disconnectWallet();
});
}
if (registerButton) {
registerButton.addEventListener("click", () => {
goToCreateDomain();
});
}
// **🔹 Truncate Wallet Address for Display**
const truncateAddress = (address) => {
return `${address.substring(0, 6)}...${address.substring(address.length - 4)}`;
};
// **🔹 Check If User Is Already Logged In**
const checkExistingSession = () => {
const storedToken = localStorage.getItem(TOKEN_KEY);
if (storedToken) {
walletButton.textContent = "Wallet Connected";
walletButton.classList.add("connected");
console.log("✅ User session found.");
}
};
// **🔹 Connect Wallet & Authenticate with MetaMask**
const connectWallet = async () => {
if (!window.ethereum) {
alert("MetaMask is not installed. Please install MetaMask.");
return;
}
const web3 = new Web3(window.ethereum);
try {
await window.ethereum.request({ method: "eth_requestAccounts" });
const accounts = await web3.eth.getAccounts();
userWallet = accounts[0];
// **🔹 Message Signing for Authentication**
const message = `Login to BIMBFA with wallet: ${userWallet}`;
const signature = await web3.eth.personal.sign(message, userWallet, "");
// **🔹 Send Login Request to Backend**
const response = await fetch("https://bimbfa.onrender.com/graphql", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
query: `
mutation {
login(walletAddress: "${userWallet}", signature: "${signature}") {
success
token
expiration
message
}
}
`,
}),
});
const result = await response.json();
console.log("🔹 Login Response:", result);
const storedToken = result.data.login.token;
if (storedToken) {
//alert("Login successful!");
// ✅ Store token in localStorage under a unique key
localStorage.setItem(TOKEN_KEY, storedToken );
walletButton.textContent = truncateAddress(userWallet);
walletButton.classList.add("connected");
console.log("🔹 Connected Wallet:", userWallet);
} else {
alert("Failed to authenticate.");
}
} catch (error) {
console.error("❌ MetaMask authentication error:", error);
}
};
// **🔹 Disconnect Wallet & Remove Token**
const disconnectWallet = () => {
userWallet = null;
walletButton.textContent = "Launch";
walletButton.classList.remove("connected");
walletOptions.style.display = "none";
// ✅ Remove only the specific token, keeping other data intact
localStorage.removeItem(TOKEN_KEY);
console.log("🔹 Wallet disconnected.");
alert("Disconnected successfully.");
};
// **🔹 Redirect User to Create Domain Page**
const goToCreateDomain = () => {
if (userWallet) {
window.location.href = "createDomain.html";
} else {
alert("You must connect your wallet first.");
}
};
// **🔹 Add JWT Token to Every Request**
const fetchWithAuth = async (query, variables = {}) => {
const token = localStorage.getItem(TOKEN_KEY);
const headers = { "Content-Type": "application/json" };
if (token) {
headers["Authorization"] = `Bearer ${token}`;
}
const response = await fetch("https://bimbfa.onrender.com/graphql", {
method: "POST",
headers,
body: JSON.stringify({ query, variables }),
});
return response.json();
};
// **🔹 Check existing session when the page loads**
checkExistingSession();
});