Files
DiunaBI/src/Backend/DiunaBI.UI.Shared/wwwroot/js/auth.js

112 lines
4.2 KiB
JavaScript
Raw Normal View History

2025-11-09 19:39:52 +01:00
let googleInitialized = false;
2025-11-06 10:20:00 +01:00
2025-11-09 19:39:52 +01:00
window.initGoogleSignIn = function(clientId) {
if (googleInitialized) {
console.log("Google Sign-In already initialized");
return;
}
2025-11-19 12:33:37 +01:00
console.log("🔐 Initializing Google Sign-In (ID Token flow)");
console.log("📋 Received clientId:", clientId);
console.log("📋 ClientId type:", typeof clientId);
console.log("📋 ClientId length:", clientId ? clientId.length : 0);
if (!clientId || clientId === '' || clientId === 'null' || clientId === 'undefined') {
console.error("❌ Invalid clientId received:", clientId);
throw new Error("ClientId is null, empty, or invalid");
}
// Check if Google library is loaded
if (typeof google === 'undefined' || !google.accounts || !google.accounts.id) {
console.error("❌ Google Sign-In library not loaded yet!");
throw new Error("Google Sign-In library not ready");
}
2025-11-09 19:39:52 +01:00
// Używamy google.accounts.id - zwraca ID token (JWT credential)
google.accounts.id.initialize({
client_id: clientId,
callback: handleCredentialResponse,
auto_select: false,
cancel_on_tap_outside: true
2025-11-06 10:20:00 +01:00
});
2025-11-19 12:33:37 +01:00
2025-11-09 19:39:52 +01:00
googleInitialized = true;
console.log("✅ Google Sign-In initialized successfully");
};
2025-11-06 10:20:00 +01:00
2025-11-09 19:39:52 +01:00
window.requestGoogleSignIn = function() {
console.log("🚀 Requesting Google Sign-In...");
// Pokaż One Tap prompt
google.accounts.id.prompt((notification) => {
if (notification.isNotDisplayed()) {
console.warn("⚠️ One Tap not displayed:", notification.getNotDisplayedReason());
} else if (notification.isSkippedMoment()) {
console.warn("⚠️ One Tap skipped:", notification.getSkippedReason());
} else {
console.log("✅ One Tap displayed");
}
2025-11-06 10:20:00 +01:00
});
2025-11-09 19:39:52 +01:00
};
2025-11-06 10:20:00 +01:00
2025-11-09 19:39:52 +01:00
function handleCredentialResponse(response) {
console.log("=== 🎉 Google Credential Response ===");
2025-11-06 10:20:00 +01:00
try {
2025-11-09 19:39:52 +01:00
if (!response.credential) {
throw new Error("No credential in response");
}
2025-11-06 10:20:00 +01:00
2025-11-09 19:39:52 +01:00
const tokenParts = response.credential.split('.');
console.log("📝 ID Token parts:", tokenParts.length); // Should be 3 (JWT)
console.log("📏 ID Token length:", response.credential.length);
if (tokenParts.length !== 3) {
throw new Error("Invalid JWT format - expected 3 parts (header.payload.signature)");
}
// Dekoduj payload JWT aby wyciągnąć user info
const payload = decodeJwtPayload(response.credential);
const fullName = payload.name || `${payload.given_name || ''} ${payload.family_name || ''}`.trim();
const email = payload.email;
const avatarUrl = payload.picture || '';
console.log("👤 User info from JWT:", { fullName, email });
console.log("📧 Email verified:", payload.email_verified);
// Wywołaj Blazor - przekaż ID token JWT (nie access token!)
DotNet.invokeMethodAsync('DiunaBI.UI.Shared', 'OnGoogleSignInSuccess',
response.credential, // <--- To jest ID token JWT dla backendu
fullName,
email,
avatarUrl)
.then(() => {
console.log("✅ Successfully sent ID token to Blazor");
})
.catch(err => {
console.error("❌ Error calling Blazor:", err);
DotNet.invokeMethodAsync('DiunaBI.UI.Shared', 'OnGoogleSignInError', err.toString());
});
2025-11-06 10:20:00 +01:00
} catch (error) {
2025-11-09 19:39:52 +01:00
console.error("❌ Error processing Google credential:", error);
DotNet.invokeMethodAsync('DiunaBI.UI.Shared', 'OnGoogleSignInError', error.toString());
2025-11-06 10:20:00 +01:00
}
2025-11-09 19:39:52 +01:00
}
2025-11-06 10:20:00 +01:00
2025-11-09 19:39:52 +01:00
function decodeJwtPayload(token) {
try {
const base64Url = token.split('.')[1];
const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
const jsonPayload = decodeURIComponent(
atob(base64)
.split('')
.map(c => '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2))
.join('')
);
return JSON.parse(jsonPayload);
} catch (error) {
console.error("Error decoding JWT:", error);
throw new Error("Invalid JWT format");
2025-11-06 10:20:00 +01:00
}
2025-11-09 19:39:52 +01:00
}