Spaces:
Running
Running
File size: 9,044 Bytes
b28567d 4a97c42 |
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 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 |
const CLIENT_ID =
"819389601271-fl7jsirpdkepkcou78erki5hmi30rrbm.apps.googleusercontent.com";
let tokenClient;
let accessToken;
async function handleCredentialResponse(response) {
const idToken = response.credential;
const payload = JSON.parse(atob(idToken.split(".")[1]));
const uid = payload.sub;
localStorage.setItem("userData", JSON.stringify({
uid: uid,
name: payload.name,
photo_profile: payload.picture,
email: payload.email,
}));
let userData = await getUserData();
if (!userData || Object.keys(userData).length === 0) {
userData = {
uid: uid,
name: payload.name,
photo_profile: payload.picture,
email: payload.email,
};
}
await updateUserDataToGitHub(userData);
localStorage.setItem("cart", JSON.stringify(userData.cart || []));
window.location.reload();
}
function handleAccessTokenResponse(response) {
accessToken = response.access_token;
console.log("Access Token:", accessToken);
fetchUserAdditionalInfo();
}
async function fetchUserAdditionalInfo() {
let userData = JSON.parse(localStorage.getItem("userData"));
if (userData && userData.uid && accessToken) {
try {
const res = await fetch(
"https://people.googleapis.com/v1/people/me?personFields=phoneNumbers,addresses",
{
headers: {
Authorization: `Bearer ${accessToken}`,
},
}
);
if (!res.ok)
throw new Error(
"Gagal mendapatkan data tambahan: " + res.status
);
const additionalData = await res.json();
console.log("Data tambahan:", additionalData);
if (
additionalData.phoneNumbers &&
additionalData.phoneNumbers.length > 0
) {
userData.phone = additionalData.phoneNumbers[0].value;
}
if (
additionalData.addresses &&
additionalData.addresses.length > 0
) {
userData.address = additionalData.addresses[0].formattedValue;
}
localStorage.setItem("userData", JSON.stringify(userData));
console.log("User Data Lengkap:", userData);
} catch (err) {
console.error("Error fetching additional info:", err);
}
} else {
console.warn("Data UID atau access token tidak tersedia.");
}
}
async function renderGoogleLoginButton() {
const container = document.getElementById("profile-container");
document.querySelectorAll("#googleSignInButton").forEach((elm) => elm.remove());
const urlNow = window.location.href;
const urlParams = new URLSearchParams(window.location.search);
const redirectUrl = urlParams.get("redirect") || urlNow;
const message =
urlParams.get("message") ||
"Silakan masuk ke akun Anda terlebih dahulu untuk melanjutkan:";
container.innerHTML = `
<p class="text-center" style="text-decoration: underline; font-style: italic;">${message}</p>
<span class="text-center m-4">Klik tombol di bawah ini untuk masuk:</span>
<div id="googleSignInButton"></div>
`;
if (message.trim()) alert(message, false);
async function loadGoogleAPI(callback) {
if (typeof google !== "undefined") {
callback();
return;
}
console.log("Memuat Google API...");
const script = document.createElement("script");
script.src = "https://accounts.google.com/gsi/client";
script.async = true;
script.defer = true;
script.onload = function () {
console.log("Google API berhasil dimuat.");
if (typeof google !== "undefined") {
callback();
} else {
console.error("Google API gagal dimuat.");
alert("Jika tombol masuk tidak tampil, silakan muat ulang halaman ini", false);
}
};
script.onerror = function () {
console.error("Gagal memuat Google API.");
alert("Gagal memuat Google Login. Coba gunakan browser lain atau muat ulang halaman ini.", false);
};
document.head.appendChild(script);
}
function initializeGoogleLogin() {
google.accounts.id.initialize({
client_id: CLIENT_ID,
callback: async (response) => {
await handleCredentialResponse(response);
window.location.href = redirectUrl;
},
auto_select: false,
button_auto_select: false,
scope: "email profile https://www.googleapis.com/auth/user.phonenumbers.read https://www.googleapis.com/auth/user.addresses.read",
});
google.accounts.id.prompt();
google.accounts.id.renderButton(
document.getElementById("googleSignInButton"),
{ theme: "outline", size: "large" }
);
}
loadGoogleAPI(() => {
initializeGoogleLogin();
});
}
async function initProfile() {
const userData = await getUserData();
if (userData && Object.keys(userData).length > 0) {
renderProfileForm(userData);
} else {
await renderGoogleLoginButton();
}
}
function renderProfileForm(userData) {
const container = document.getElementById("profile-container");
container.innerHTML = `
<form id="profileForm" class="fs-5">
<div class="mb-2 d-flex flex-row align-items-center justify-content-center">
<img id="photo_profile" class="img-fluid img-thumbnail rounded-circle" src=${userData.photo_profile}>
<input class="d-none" type="file" id="fileInput" accept="image/*">
</div>
<div class="mb-2">
<input class="form-control form-control-lg" type="text" id="name" placeholder="Nama" value="${
userData.name || ""
}" required>
</div>
<div class="mb-2">
<input class="form-control form-control-lg" type="email" id="email" placeholder="Email" value="${
userData.email || ""
}" required disabled>
</div>
<div class="mb-2">
<input class="form-control form-control-lg" type="text" id="phone" placeholder="No. HP" value="${
userData.phone || ""
}" required>
</div>
<div class="mb-2">
<input class="form-control form-control-lg" type="text" id="address" placeholder="Alamat" value="${
userData.address || ""
}" required>
</div>
<br>
<button class="btn btn-primary btn-lg" type="button" id="saveProfile">Simpan</button>
<br><br>
<button class="btn btn-danger btn-lg" type="button" id="logout">Keluar Akun</button>
</form>`;
document.getElementById("photo_profile").addEventListener("click", function () {
document.getElementById("fileInput").click();
});
document.getElementById("fileInput").addEventListener("change", function (event) {
const file = event.target.files[0];
if (file) {
if (file.size > 1 * 1024 * 1024) {
alert("Ukuran file terlalu besar! Maksimal 1MB.", false);
return;
}
const reader = new FileReader();
reader.onload = function (e) {
document.getElementById("photo_profile").src = e.target.result;
};
reader.readAsDataURL(file);
}
});
document
.getElementById("saveProfile")
.addEventListener("click", async function () {
const updatedUser = {
uid: userData.uid,
name: document.getElementById("name").value.trim(),
email: userData.email,
phone: document.getElementById("phone").value.trim(),
address: document.getElementById("address").value.trim(),
photo_profile: document.getElementById("photo_profile").src,
cart: userData.cart ? userData.cart : [],
transactions: userData.transactions
? userData.transactions
: [],
};
if (
!updatedUser.name ||
!updatedUser.email ||
!updatedUser.phone ||
!updatedUser.address
) {
alert("Semua input wajib diisi!", false);
return;
}
localStorage.setItem("userData", JSON.stringify(updatedUser));
await updateUserDataToGitHub(updatedUser);
alert("Profil berhasil disimpan!", false);
});
document.getElementById("logout").addEventListener("click", function () {
localStorage.removeItem("userData");
window.location.reload();
});
}
document.addEventListener("DOMContentLoaded", function () {
AOS.init();
initProfile();
});
|