OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

Stay signed in Google Cloud Calendar API

  • Thread starter Thread starter Hugo Jiménez
  • Start date Start date
H

Hugo Jiménez

Guest
I have a web application that allows me to see the calendar of the Google account that logs in. I have this code:

Code:
<script>
        let config;

        async function loadConfig() {
            const response = await fetch('./keys/google.json');
            config = await response.json();
            gapi.load('client', initializeGapiClient);
        }

        async function initializeGapiClient() {
            // Mostrar una animación de carga mientras se carga el calendario de Google
            Swal.fire({
                title: 'Cargando Calendario de Google...',
                allowOutsideClick: false,
                didOpen: () => {
                    Swal.showLoading();
                }
            });

            try {
                await gapi.client.init({
                    apiKey: config.api_key,
                    discoveryDocs: [config.discovery_doc],
                });
                fetchEvents();
            } catch (error) {
                console.error('Error initializing Google API client', error);
                Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    text: 'Ocurrió un error al cargar el calendario de Google. Por favor, inténtalo de nuevo más tarde.'
                });
            } finally {
                // Cerrar la animación de carga una vez inicializado el cliente de Google API
                Swal.close();
            }
        }

        async function fetchEvents() {
            const token = localStorage.getItem('googleAccessToken');
            if (token) {
                gapi.client.setToken({ access_token: token });
                try {
                    const response = await gapi.client.calendar.events.list({
                        'calendarId': 'primary',
                        'timeMin': '2020-01-01T00:00:00Z',  // Fecha y hora mínima para obtener eventos
                        'showDeleted': false,
                        'singleEvents': true,
                        'maxResults': 10,
                        'orderBy': 'startTime',
                    });
                    
                    let events = response.result.items.map(event => ({
                        title: event.summary,
                        start: event.start.dateTime || event.start.date,
                        end: event.end.dateTime || event.end.date,
                    }));

                    // Verificar si hay más eventos disponibles y recuperarlos
                    let nextPageToken = response.result.nextPageToken;
                    while (nextPageToken) {
                        const additionalResponse = await gapi.client.calendar.events.list({
                            'calendarId': 'primary',
                            'timeMin': '2020-01-01T00:00:00Z',
                            'showDeleted': false,
                            'singleEvents': true,
                            'maxResults': 10,
                            'orderBy': 'startTime',
                            'pageToken': nextPageToken,
                        });

                        events = events.concat(additionalResponse.result.items.map(event => ({
                            title: event.summary,
                            start: event.start.dateTime || event.start.date,
                            end: event.end.dateTime || event.end.date,
                        })));

                        nextPageToken = additionalResponse.result.nextPageToken;
                    }

                    renderCalendar(events);
                    Swal.close();
                } catch (err) {
                    console.error('Error fetching events', err);
                    Swal.fire({
                        icon: 'error',
                        title: 'Error al cargar eventos',
                        text: 'Ocurrió un error al intentar cargar los eventos. Por favor, inténtalo de nuevo más tarde.'
                    });
                    Swal.close();
                }
            } else {
                console.error('No se encontró ningún token de acceso');
                Swal.fire({
                    icon: 'error',
                    title: 'No se encontró token de acceso',
                    text: 'No se encontró ningún token de acceso. Por favor, inicia sesión nuevamente.'
                });
                Swal.close();
            }
        }

        function renderCalendar(events) {
            const calendarEl = document.getElementById('calendar');
            const calendar = new FullCalendar.Calendar(calendarEl, {
                customButtons: {
                    myCustomButton: {
                        text: '🔄 Refrescar',
                        click: function () {
                            Swal.fire({
                                title: 'Actualizando eventos...',
                                allowOutsideClick: false,
                                didOpen: () => {
                                    Swal.showLoading();
                                    fetchEvents();
                                },
                            });
                        },
                    },
                    logout: {
                        text: '❌ Cerrar Sesión',
                        click: () => {
                            console.log('Cerrando sesion Google...');
                            Swal.fire({
                                title: 'Cerrando sesión...',
                                allowOutsideClick: false,
                                didOpen: () => {
                                    Swal.showLoading();
                                },
                            });
                            try {
                                localStorage.removeItem('googleAccessToken');
                                localStorage.setItem('logoutCompletedG', 'true');
                                console.log('Sesion Google cerrada correctamente');
                                Swal.close();
                                window.location.href = 'local.html';
                            } catch (error) {
                                Swal.close();
                                Swal.fire({
                                    icon: 'error',
                                    title: 'Error al cerrar sesión',
                                    text: 'Ocurrió un error al intentar cerrar sesión. Por favor, inténtalo de nuevo más tarde.'
                                });
                                console.log('Error al cerrar sesion Google');
                            }
                        }
                    }
                },
                headerToolbar: {
                    left: 'prev,next today myCustomButton logout',
                    center: 'title',
                    right: 'dayGridMonth,timeGridWeek,timeGridDay'
                },
                buttonText: {
                    today: 'Hoy',
                    month: 'Mes',
                    week: 'Semana',
                    day: 'Día',
                    list: 'Lista'
                },
                initialView: 'dayGridMonth',
                locale: 'es',
                firstDay: 1,
                events: events,
                dayMaxEvents: true,
                eventClick: function (info) {
                    const event = info.event;
                    const title = event.title;
                    const start = event.start;
                    const end = event.end;
                    const allDay = event.allDay;
                    const location = event.extendedProps.location;
                    const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;
                    const startFormatted = start.toLocaleString('es-ES', { timeZone: timeZone });
                    const endFormatted = end ? end.toLocaleString('es-ES', { timeZone: timeZone }) : 'Evento de todo el día';
                    let content = `<h2>${title}</h2>`;
                    if (!allDay) {
                        content += `<p><strong>Inicio:</strong> ${startFormatted}</p>`;
                        content += `<p><strong>Fin:</strong> ${endFormatted}</p>`;
                    } else {
                        content += `<p><strong>Evento de todo el día</strong></p>`;
                    }
                    if (location) {
                        content += `<p><strong>Ubicación:</strong> ${location}</p>`;
                    }
                    Swal.fire({
                        title: 'Información del Evento',
                        html: content,
                        icon: 'info'
                    });
                }
            });
            calendar.render();
        }

        loadConfig();
    </script>

Is there a way to keep the session logged in with a Google account even when refreshing the website or closing the browser?

I have seen that my problem was asked here: Stay signed in Google Calendar but my question, seeing the comments and answers, is more related to the part of the code is knowing if I can store the access token in some way to avoid each time access is attempted, not only authorization but also authentication.

I had thought about using a refresh token but I don't know exactly how to use it

thanks a lot!!
<p>I have a web application that allows me to see the calendar of the Google account that logs in.
I have this code:</p>
<pre><code><script>
let config;

async function loadConfig() {
const response = await fetch('./keys/google.json');
config = await response.json();
gapi.load('client', initializeGapiClient);
}

async function initializeGapiClient() {
// Mostrar una animación de carga mientras se carga el calendario de Google
Swal.fire({
title: 'Cargando Calendario de Google...',
allowOutsideClick: false,
didOpen: () => {
Swal.showLoading();
}
});

try {
await gapi.client.init({
apiKey: config.api_key,
discoveryDocs: [config.discovery_doc],
});
fetchEvents();
} catch (error) {
console.error('Error initializing Google API client', error);
Swal.fire({
icon: 'error',
title: 'Error',
text: 'Ocurrió un error al cargar el calendario de Google. Por favor, inténtalo de nuevo más tarde.'
});
} finally {
// Cerrar la animación de carga una vez inicializado el cliente de Google API
Swal.close();
}
}

async function fetchEvents() {
const token = localStorage.getItem('googleAccessToken');
if (token) {
gapi.client.setToken({ access_token: token });
try {
const response = await gapi.client.calendar.events.list({
'calendarId': 'primary',
'timeMin': '2020-01-01T00:00:00Z', // Fecha y hora mínima para obtener eventos
'showDeleted': false,
'singleEvents': true,
'maxResults': 10,
'orderBy': 'startTime',
});

let events = response.result.items.map(event => ({
title: event.summary,
start: event.start.dateTime || event.start.date,
end: event.end.dateTime || event.end.date,
}));

// Verificar si hay más eventos disponibles y recuperarlos
let nextPageToken = response.result.nextPageToken;
while (nextPageToken) {
const additionalResponse = await gapi.client.calendar.events.list({
'calendarId': 'primary',
'timeMin': '2020-01-01T00:00:00Z',
'showDeleted': false,
'singleEvents': true,
'maxResults': 10,
'orderBy': 'startTime',
'pageToken': nextPageToken,
});

events = events.concat(additionalResponse.result.items.map(event => ({
title: event.summary,
start: event.start.dateTime || event.start.date,
end: event.end.dateTime || event.end.date,
})));

nextPageToken = additionalResponse.result.nextPageToken;
}

renderCalendar(events);
Swal.close();
} catch (err) {
console.error('Error fetching events', err);
Swal.fire({
icon: 'error',
title: 'Error al cargar eventos',
text: 'Ocurrió un error al intentar cargar los eventos. Por favor, inténtalo de nuevo más tarde.'
});
Swal.close();
}
} else {
console.error('No se encontró ningún token de acceso');
Swal.fire({
icon: 'error',
title: 'No se encontró token de acceso',
text: 'No se encontró ningún token de acceso. Por favor, inicia sesión nuevamente.'
});
Swal.close();
}
}

function renderCalendar(events) {
const calendarEl = document.getElementById('calendar');
const calendar = new FullCalendar.Calendar(calendarEl, {
customButtons: {
myCustomButton: {
text: '🔄 Refrescar',
click: function () {
Swal.fire({
title: 'Actualizando eventos...',
allowOutsideClick: false,
didOpen: () => {
Swal.showLoading();
fetchEvents();
},
});
},
},
logout: {
text: '❌ Cerrar Sesión',
click: () => {
console.log('Cerrando sesion Google...');
Swal.fire({
title: 'Cerrando sesión...',
allowOutsideClick: false,
didOpen: () => {
Swal.showLoading();
},
});
try {
localStorage.removeItem('googleAccessToken');
localStorage.setItem('logoutCompletedG', 'true');
console.log('Sesion Google cerrada correctamente');
Swal.close();
window.location.href = 'local.html';
} catch (error) {
Swal.close();
Swal.fire({
icon: 'error',
title: 'Error al cerrar sesión',
text: 'Ocurrió un error al intentar cerrar sesión. Por favor, inténtalo de nuevo más tarde.'
});
console.log('Error al cerrar sesion Google');
}
}
}
},
headerToolbar: {
left: 'prev,next today myCustomButton logout',
center: 'title',
right: 'dayGridMonth,timeGridWeek,timeGridDay'
},
buttonText: {
today: 'Hoy',
month: 'Mes',
week: 'Semana',
day: 'Día',
list: 'Lista'
},
initialView: 'dayGridMonth',
locale: 'es',
firstDay: 1,
events: events,
dayMaxEvents: true,
eventClick: function (info) {
const event = info.event;
const title = event.title;
const start = event.start;
const end = event.end;
const allDay = event.allDay;
const location = event.extendedProps.location;
const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;
const startFormatted = start.toLocaleString('es-ES', { timeZone: timeZone });
const endFormatted = end ? end.toLocaleString('es-ES', { timeZone: timeZone }) : 'Evento de todo el día';
let content = `<h2>${title}</h2>`;
if (!allDay) {
content += `<p><strong>Inicio:</strong> ${startFormatted}</p>`;
content += `<p><strong>Fin:</strong> ${endFormatted}</p>`;
} else {
content += `<p><strong>Evento de todo el día</strong></p>`;
}
if (location) {
content += `<p><strong>Ubicación:</strong> ${location}</p>`;
}
Swal.fire({
title: 'Información del Evento',
html: content,
icon: 'info'
});
}
});
calendar.render();
}

loadConfig();
</script>
</code></pre>
<p>Is there a way to keep the session logged in with a Google account even when refreshing the website or closing the browser?</p>
<p>I have seen that my problem was asked here: <a href="https://stackoverflow.com/questions/73503633/stay-signed-in-google-calendar">Stay signed in Google Calendar</a> but my question, seeing the comments and answers, is more related to the part of the code is knowing if I can store the access token in some way to avoid each time access is attempted, not only authorization but also authentication.</p>
<p>I had thought about using a refresh token but I don't know exactly how to use it</p>
<p>thanks a lot!!</p>
Continue reading...
 

Latest posts

Top