Skip to content

Instantly share code, notes, and snippets.

@thesandlord
Last active January 30, 2021 16:55
Show Gist options
  • Save thesandlord/4740bfaca43d67fe6865c097db2a4016 to your computer and use it in GitHub Desktop.
Save thesandlord/4740bfaca43d67fe6865c097db2a4016 to your computer and use it in GitHub Desktop.
/**
* @license
* Copyright 2018, Google, Inc.
* Licensed under the Apache License, Version 2.0 (the 'License');
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an 'AS IS' BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var config = {
// REPLACE WITH THE CONFIG OBJECT YOU CREATED
// https://medium.com/@SandeepDinesh/using-google-apis-with-firebase-auth-and-firebase-ui-on-the-web-46e6189cf571
};
firebase.initializeApp(config);
var uiConfig = {
signInSuccessUrl: "localhost:5000", // Assuming you are running on your local machine
signInOptions: [
{
provider: firebase.auth.GoogleAuthProvider.PROVIDER_ID,
scopes: config.scopes
}
],
// Terms of service url.
tosUrl: "<your-tos-url>"
};
// Initialize the FirebaseUI Widget using Firebase.
var ui = new firebaseui.auth.AuthUI(firebase.auth());
// The start method will wait until the DOM is loaded.
ui.start("#firebaseui-auth-container", uiConfig);
// This function will trigger when there is a login event
firebase.auth().onAuthStateChanged(function(user) {
console.log(user)
// Make sure there is a valid user object
if (user) {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "https://apis.google.com/js/api.js";
// Once the Google API Client is loaded, you can run your code
script.onload = function(e) {
// Initialize the Google API Client with the config object
gapi.client
.init({
apiKey: config.apiKey,
clientId: config.clientID,
discoveryDocs: config.discoveryDocs,
scope: config.scopes.join(" ")
})
// Loading is finished, so start the app
.then(function() {
// Make sure the Google API Client is properly signed in
if (gapi.auth2.getAuthInstance().isSignedIn.get()) {
startApp(user);
} else {
firebase.auth().signOut(); // Something went wrong, sign out
}
});
};
// Add to the document
document.getElementsByTagName("head")[0].appendChild(script);
}
});
function startApp(user) {
console.log(user);
// Make sure to refresh the Auth Token in case it expires!
firebase.auth().currentUser.getToken()
.then(function(){
return gapi.client.calendar.events
.list({
calendarId: "primary",
timeMin: new Date().toISOString(),
showDeleted: false,
singleEvents: true,
maxResults: 10,
orderBy: "startTime"
})
})
.then(function(response) {
console.log(response);
});
}
@gmcnaughton
Copy link

gmcnaughton commented Apr 17, 2018

Thanks for this sample, it was a huge help!

Heads up about a couple possible issues:

  • The client.init code passes config.clientID, but the key is config.clientId (lowercase d). This was causing the error: "client_id and scope must both be provided to initialize OAuth"
  • I needed to call client.load to init gapi first, otherwise gapi.client was undefined. (This may be because I was using firebase.auth().signInWithPopup explicitly instead of going through firebaseui)
gapi.load('client', {
  callback: function() {
    gapi.client.init ...
  },
  ...
})

After getting everything initialized, trying to hit an api (like Google Drive) failed with 403 errors until I enabled that API for my project:

"message": "Access Not Configured. Drive API has not been used in project 123 before or it is disabled. Enable it by visiting https://console.developers.google.com/apis/api/drive.googleapis.com/overview?project=123 then retry. If you enabled this API recently, wait a few minutes for the action to propagate to our systems and retry."

@diazabdulm
Copy link

On line 78, change getToken() to getIdToken(true) otherwise an error saying that it is not a function will pop up.

@drKnoxy
Copy link

drKnoxy commented Sep 15, 2018

@gmcnaughton just wanted to say thanks for the additional notes. Had to do the client.load step to get the lib pulled in before i could access gapi.client.people.people...

my other typo was writing "scopes" instead of "scope" in init, which resulted in the same error line @_@

Thanks for the medium article and this snippet @thesandlord

@godie2017
Copy link

godie2017 commented Mar 25, 2019

Hi @thesandlord, I'm trying to implement your code to modify a google spreadsheet, but it still does not work for me. Could you help me please?
I'm new developing and I do not know what is wrong. Thanks for the help!!

This is the code:

 var config = {
    apiKey: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
    authDomain: "xxxxxxxxxxxxxxxxxxxxxx",
    databaseURL: "xxxxxxxxxxxxxxxxxxxxxxxx",
    projectId: "xxxxxxxxxxx",
    storageBucket: "xxxxxxxxxxxxxxx",
    messagingSenderId: "xxxxxxxxxxxx",
    clientId: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com",
    scope: [
         "email",
         "profile",
         "https://www.googleapis.com/auth/spreadsheets"
    ],
    discoveryDocs: [
        "https://sheets.googleapis.com/$discovery/rest?version=v4"
        ]
  };
  firebase.initializeApp(config);


var AuthGoogle = new firebase.auth.GoogleAuthProvider();

$('#Google').click(function(){   
    firebase.auth().signInWithPopup(AuthGoogle).then(function(result) {

        }).catch(function(error) {
          // Handle Errors here.
          var errorCode = error.code;
          var errorMessage = error.message;
            console.log(errorMessage);
        });
});     
    
    

var uiConfig = {
  signInSuccessUrl: "localhost:5000", // Assuming you are running on your local machine
  signInOptions: [
    {
      provider: firebase.auth.GoogleAuthProvider.PROVIDER_ID,
      scope: config.scope
    }
  ],

  // Terms of service url.
  tosUrl: "<your-tos-url>"
};

firebase.auth().onAuthStateChanged(function(user) {
  // Make sure there is a valid user object
  if(user){
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = 'https://apis.google.com/js/api.js';
    // Once the Google API Client is loaded, you can run your code
    script.onload = function(e){
     // Initialize the Google API Client with the config object
    
        gapi.load('client', {
          callback: function() {
            gapi.client.init({
               apiKey: config.apiKey,
               clientId: config.clientId,
               discoveryDocs: config.discoveryDocs,
               scope: config.scope.join(' '),
            })
            .then(function() {
              // Make sure the Google API Client is properly signed in
              if (gapi.auth2.getAuthInstance().isSignedIn.get()) {
                startApp(user);
              } else {
                firebase.auth().signOut(); // Something went wrong, sign out
              }
            })
          }
        })   
    }
    // Add to the document
    document.getElementsByTagName('head')[0].appendChild(script);  
 }else{
      console.log('no hay usuario')  //AFTER DOING EVERYTHING WITHOUT ERRORS, ALWAYS REACH THIS POINT AND DO NOTHING!!
  }
});

var params = {
    spreadsheetId: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', 
    range: 'Solicitudes', 
    valueInputOption: 'RAW', 
    insertDataOption: 'INSERT_ROW'
};

var valueRangeBody = {
    "majorDimension": "ROWS",
    "range": "Solicitudes",
    "values": [
      [
        "Guardando desde mi api1",
        "Guardando desde mi api2"
      ]
    ]
};        
 
function startApp(user) {
  console.log(user);
    firebase.auth().currentUser.getIdToken(true)
    .then(function(){ 
  return gapi.client.sheets.spreadsheets.values.append(params, valueRangeBody)})
        .then(function(response) {
    console.log(response.result);
  });
}

sorry for may inglish.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment