Recent sheets per user
This commit is contained in:
@@ -5,6 +5,7 @@ import { env } from '$env/dynamic/public';
|
||||
export const accessToken = writable<string | null | undefined>(undefined);
|
||||
export const isSignedIn = writable(false);
|
||||
export const isGoogleApiReady = writable(false); // To track GAPI client readiness
|
||||
export const userEmail = writable<string | null>(null);
|
||||
|
||||
let tokenClient: google.accounts.oauth2.TokenClient;
|
||||
let gapiInited = false;
|
||||
@@ -48,6 +49,27 @@ export function initGoogleClients(callback: () => void) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches user's email and stores it.
|
||||
*/
|
||||
async function fetchUserInfo(token: string) {
|
||||
try {
|
||||
const response = await fetch('https://www.googleapis.com/oauth2/v3/userinfo', {
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`
|
||||
}
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to fetch user info');
|
||||
}
|
||||
const profile = await response.json();
|
||||
userEmail.set(profile.email);
|
||||
} catch (error) {
|
||||
console.error('Error fetching user info:', error);
|
||||
userEmail.set(null);
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Load GSI script for Auth. This should only be called after GAPI is ready.
|
||||
function initGsiClient(callback: () => void) {
|
||||
if (gsiInited) {
|
||||
@@ -64,7 +86,7 @@ function initGsiClient(callback: () => void) {
|
||||
tokenClient = google.accounts.oauth2.initTokenClient({
|
||||
client_id: env.PUBLIC_GOOGLE_CLIENT_ID,
|
||||
scope:
|
||||
'https://www.googleapis.com/auth/drive.readonly https://www.googleapis.com/auth/spreadsheets.readonly',
|
||||
'https://www.googleapis.com/auth/drive.readonly https://www.googleapis.com/auth/spreadsheets.readonly https://www.googleapis.com/auth/userinfo.email',
|
||||
callback: (tokenResponse) => {
|
||||
// This callback handles responses from all token requests.
|
||||
if (tokenResponse.error) {
|
||||
@@ -78,6 +100,7 @@ function initGsiClient(callback: () => void) {
|
||||
isSignedIn.set(true);
|
||||
// Also set the token for the GAPI client
|
||||
if (gapiInited) gapi.client.setToken({ access_token: token });
|
||||
fetchUserInfo(token);
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -152,6 +175,7 @@ export function handleSignOut() {
|
||||
}
|
||||
accessToken.set(null);
|
||||
isSignedIn.set(false);
|
||||
userEmail.set(null);
|
||||
|
||||
console.log('User signed out.');
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user