0

index.html

  1. When I click Authorize, Google signs in, but when I refresh the page, it prompts me to sign in to Google once more. What can I do to stay signed in until the user signs out? Here I tried javascript calendar API to insert an event into Google Calendar.

  2. I'm using the Google Calendar API and I'm trying to keep the user signed in when they reload the page but I'm having trouble with it. I can't find anything online about this.

<!DOCTYPE html>
<html>
   <head>
      <title>Google Calendar API Quickstart</title>
      <meta charset="utf-8" />
   </head>
   <body>
      <p>Google Calendar API Quickstart</p>
      <!--Add buttons to initiate auth sequence and sign out-->
      <button id="authorize_button" onclick="handleAuthClick()">Authorize</button>
      <button id="signout_button" onclick="handleSignoutClick()">Sign Out</button>
      <button id="addto_cal" onclick="addto_cal()">Add to calendar</button>
      <pre id="content" style="white-space: pre-wrap;"></pre>
      <script type="text/javascript">
         /* exported gapiLoaded */
         /* exported gisLoaded */
         /* exported handleAuthClick */
         /* exported handleSignoutClick */
         
         // TODO(developer): Set to client ID and API key from the Developer Console
         const CLIENT_ID = 'my_client_id';
         const API_KEY = 'my_api_key';
         
         // Discovery doc URL for APIs used by the quickstart
         const DISCOVERY_DOC = 'https://www.googleapis.com/discovery/v1/apis/calendar/v3/rest';
         
         // Authorization scopes required by the API; multiple scopes can be
         // included, separated by spaces.
         const SCOPES = 'https://www.googleapis.com/auth/calendar';
         
         let tokenClient;
         let gapiInited = false;
         let gisInited = false;
         
         document.getElementById('authorize_button').style.visibility = 'hidden';
         document.getElementById('signout_button').style.visibility = 'hidden';
         document.getElementById('addto_cal').style.visibility = 'hidden';
         
         /**
          * Callback after api.js is loaded.
          */
         function gapiLoaded() {
           gapi.load('client', intializeGapiClient);
         }
         
         /**
          * Callback after the API client is loaded. Loads the
          * discovery doc to initialize the API.
          */
         async function intializeGapiClient() {
           await gapi.client.init({
             apiKey: API_KEY,
             discoveryDocs: [DISCOVERY_DOC],
           });
           gapiInited = true;
           maybeEnableButtons();
         }
         
         /**
          * Callback after Google Identity Services are loaded.
          */
         function gisLoaded() {
           tokenClient = google.accounts.oauth2.initTokenClient({
             client_id: CLIENT_ID,
             scope: SCOPES,
             callback: '', // defined later
           });
           gisInited = true;
           maybeEnableButtons();
         }
         
         /**
          * Enables user interaction after all libraries are loaded.
          */
         function maybeEnableButtons() {
           if (gapiInited && gisInited) {
             document.getElementById('authorize_button').style.visibility = 'visible';
           }
         }
         
         /**
          *  Sign in the user upon button click.
          */
         function handleAuthClick() {
           tokenClient.callback = async (resp) => {
             if (resp.error !== undefined) {
               throw (resp);
             }
             document.getElementById('signout_button').style.visibility = 'visible';
             document.getElementById('authorize_button').innerText = 'Refresh';
             document.getElementById('addto_cal').style.visibility = 'visible';
             //window.location.replace("success_user.jsp");
             //window.history.pushState('page2', 'Title', 'inbetween.jsp');
             await listUpcomingEvents();
           };
         
           if (gapi.client.getToken() === null) {
             // Prompt the user to select a Google Account and ask for consent to share their data
             // when establishing a new session.
             tokenClient.requestAccessToken({prompt: 'consent'});
           } else {
             // Skip display of account chooser and consent dialog for an existing session.
             tokenClient.requestAccessToken({prompt: ''});
           }
         }
         
         /**
          *  Sign out the user upon button click.
          */
         function handleSignoutClick() {
           const token = gapi.client.getToken();
           if (token !== null) {
             google.accounts.oauth2.revoke(token.access_token);
             gapi.client.setToken('');
             document.getElementById('content').innerText = '';
             document.getElementById('authorize_button').innerText = 'Authorize';
             document.getElementById('signout_button').style.visibility = 'hidden';
             document.getElementById('addto_cal').style.visibility = 'hidden';
           }
         }
         
         function addto_cal()
         {
           try {
             var resource = {
               "summary": "Vimal Bus Booking",
               "location": "Chennai",
                 'description': "Trichy to Chennai at 9:00 PM",
               "start": {
                 "dateTime": "2022-08-30T10:00:00.000-07:00"
               },
               "end": {
                 "dateTime": "2022-09-01T10:25:00.000-07:00"
                 }
               };
             var request = gapi.client.calendar.events.insert({
               'calendarId': 'primary',
               'resource': resource
             });
             request.execute(function(resp) {
               console.log(resp);
             });   
           } 
           
           catch (err) {
             document.getElementById('content').innerText = err.message;
             return;
           }
         }
         /**
          * Print the summary and start datetime/date of the next ten events in
          * the authorized user's calendar. If no events are found an
          * appropriate message is printed.
          */
         async function listUpcomingEvents() {
           let response;
           try {
             const request = {
               'calendarId': 'primary',
               'timeMin': (new Date()).toISOString(),
               'showDeleted': false,
               'singleEvents': true,
               'maxResults': 10,
               'orderBy': 'startTime',
             };
             response = await gapi.client.calendar.events.list(request);
           } catch (err) {
             document.getElementById('content').innerText = err.message;
             return;
           }
         
           const events = response.result.items;
           if (!events || events.length == 0) {
             document.getElementById('content').innerText = 'No events found.';
             return;
           }
           // Flatten to string to display
           const output = events.reduce(
               (str, event) => `${str}${event.summary} (${event.start.dateTime || event.start.date})\n`,
               'Events:\n');
           document.getElementById('content').innerText = output;
         }
      </script>
      <script async defer src="https://apis.google.com/js/api.js" onload="gapiLoaded()"></script>
      <script async defer src="https://accounts.google.com/gsi/client" onload="gisLoaded()"></script>
   </body>
</html>
Vimal M
  • 13
  • 1
  • 4
  • Please trim your code to make it easier to find your problem. Follow these guidelines to create a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example). – Community Aug 30 '22 at 20:00

1 Answers1

2
  1. Technically you can't stay signed in after the page reload - all state data is lost, so JS code have to redo all process of sign-in.
  2. But to make life easier you can somehow save access token and use it to speed-up things after page reload. That's what Google lib should do behind scenes - save to cookies or something like that. And it looks like it fails to do so in your case, because of browser or Google security policy, some privacy tool, bug - there are many possible reasons. Did you check browser console for errors?
Sam O'Riil
  • 46
  • 5
  • Thanks for helping with this matter sam, Can you please give some references like how to store and check access token in the javascript calendar API, or any implementation regarding the same? – Vimal M Aug 31 '22 at 09:27
  • @VimalM, no. I had implemented sign-in via Google several times for different sites, but nothing more than that. You problem seems to be on the first part - auth with Google, not the next one - service API, so I has answered. – Sam O'Riil Aug 31 '22 at 14:31
  • @VimalM you have gapi.client.getToken and gapi.client.setToken so all you need is just to save token between page refreshes. I.e. in localStorage or server backend. Depends on your security model. – Sam O'Riil Aug 31 '22 at 14:36
  • So, anyone please, how can I get my name, id, and email using the **javascript calendar API**? – Vimal M Sep 01 '22 at 07:45
  • @VimalM It is not a part of Calendar API, it's in OAuth2 API and you should request proper scopes for it - `email` and `profile`. After that you can get id, name, email, and some other data via calls like `gapi.auth2.getAuthInstance().currentUser.get().getBasicProfile().getName()` – Sam O'Riil Sep 01 '22 at 15:21
  • Thanks a lot, sam. After setting the required scope, I can able to retrieve the userinfo. – Vimal M Sep 02 '22 at 05:01