Coder Social home page Coder Social logo

vue-gapi / vue-gapi Goto Github PK

View Code? Open in Web Editor NEW
135.0 7.0 41.0 4.83 MB

[Deprecated] Google API Client Library wrapper for Vue.js

Home Page: https://vue-gapi.github.io/vue-gapi/

License: MIT License

JavaScript 96.68% HTML 3.32%
vue vuejs google google-api gapi

vue-gapi's Introduction

npm vuejs3

VueGapi

Google API Client Library wrapper for Vue.js

⚠️ Deprecation

The Google Sign-In JavaScript Platform Library is deprecated and will be fully retired on March 31, 2023. This plugin will not be receiving new features.

We would encourage you to migrate your application to Vue3 Google Sign-in which exposes a number of Vue 3 composables built on the new Google Identity Services library.

Requirements

Version 2 requires Vue 3.

If you are looking for a Vue 2 compatible version, use Version 1.

Installation

npm install vue-gapi

Usage

Install the plugin with gapi.client.init configuration parameters:

import { createApp } from 'vue'
import VueGapi from 'vue-gapi'

const app = createApp({})

app.use(VueGapi, {
  apiKey: '<YOUR_API_KEY>',
  clientId: '<YOUR_CLIENT_ID>.apps.googleusercontent.com',
  discoveryDocs: ['https://sheets.googleapis.com/$discovery/rest?version=v4'],
  scope: 'https://www.googleapis.com/auth/spreadsheets',
})

Composition API

Inject the GoogleAuthService instance via useGapi:

import { useGapi } from 'vue-gapi'

export default {
  setup() {
    const gapi = useGapi()

    function login() {
      gapi.login().then(({ currentUser, gapi, hasGrantedScopes }) => {
        console.log({ currentUser, gapi, hasGrantedScopes })
      })
    }

    return { login }
  },
}

Options API

Reference the $gapi global property accessible inside the application:

export default {
  methods: {
    login() {
      this.$gapi.login().then(({ currentUser, gapi, hasGrantedScopes }) => {
        console.log({ currentUser, gapi, hasGrantedScopes })
      })
    },
  },
}

vue-gapi's People

Contributors

cedlv avatar cedpoilly avatar decodeit avatar dependabot-preview[bot] avatar dependabot[bot] avatar everttrollip avatar fmeyertoens avatar fraunos avatar hanliao avatar hkd987 avatar namoscato avatar pavelkrejsa avatar rcastera avatar sadortun avatar thomasleveil avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

vue-gapi's Issues

Version 1.0

(Working) Release Notes

Version 1.0 unifies a promise-based API and improves the internal software architecture.

Breaking Changes

Session Storage

The local storage keys in which this plugin interacts with have been consolidated into a single key. The existing keys are no longer referenced, and users will need to login again to initialize their session.

Configuration

The refreshToken plugin configuration option was moved to an optional login option. The plugin options now match gapi.client.init configuration parameters exactly and are only used for that purpose.

If your application relied on offline access functionality, remove the plugin option:

Vue.use(VueGapi, {
   apiKey: '<YOUR_API_KEY>',
   clientId: '<YOUR_CLIENT_ID>.apps.googleusercontent.com',
   discoveryDocs: ['https://sheets.googleapis.com/$discovery/rest?version=v4'],
   scope: 'https://www.googleapis.com/auth/spreadsheets',
-  // works only with `ux_mode: "prompt"`
-  refreshToken: true,
 })

and update the arguments to login:

-this.$gapi.login()
+this.$gapi.login({ grantOfflineAccess: true })

Methods

  • Remove all deprecated methods (exposed directly on the Vue prototype)
  • Remove grant resolve / reject callback arguments
  • Add GoogleUser argument to hasGrantedRequestedScopes
  • Return promise from isSignedIn (instead of a boolean)
  • listenUserSignIn
    • Invoke once on initialization
    • Return a void promise
  • login
    • Remove resolve / reject callback arguments
    • Rename resolved googleUser property to currentUser
  • Remove logout resolve / reject callback arguments

Features

  • Add getAuthInstance
  • Add getCurrentUser
  • Persist getOfflineAccessCode in local storage
  • Resolve grantOfflineAccess with the authorization code
  • Resolve login with the authorization code when grantOfflineAccess: true

Internal

  • Introduce GapiClientProvider to abstract asynchronous gapi script loading
  • Introduce SessionStorage to abstract local storage interactions
  • Simplify Vue plugin configuration by exposing GoogleAuthService instance directly
  • Introduce simple example implementation
  • Improve test coverage

Missing required authentication credential

Hi,

Thank you for this library! I am trying to create a form that, when submitted, writes data to a Google sheet. I used vue-gapi and configured it as specified, but when I click my submit button I get the following error: "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential."
This is the code that sets up the API:

import VueGAPI from 'vue-gapi'
const apiConfig = {
  apiKey: 'MY_KEY',
  clientId: 'MY_ID',
  discoveryDocs: ['https://sheets.googleapis.com/$discovery/rest?version=v4'],
  scope: 'https://www.googleapis.com/auth/spreadsheets'
}

Vue.use(VueGAPI, apiConfig)

This is the code that tries to write to the sheet:

this.$getGapiClient().then((gapi) => {
          const params = {
            spreadsheetId: '1IZfst0hsjboYwn8KZe-oAbQj8LBPZDBKmBHnoQA-nsE',
            range: 'Sheet1',
            valueInputOption: 'RAW',
            insertDataOption: 'INSERT_ROWS'
          }
          const valueRangeBody = {
            majordimension: 'ROWS',
            values: ['testing', 'testing', 'testing', 'testing', 'testing', 'testing', 'testing', 'testing']
          }
          let request = gapi.client.sheets.spreadsheets.values.append(params, valueRangeBody)
          request.then(
            function (response) {
              console.log(response.result)
              alert(
                'The form has been submitted. Thank you for your help updating the entry!'
              )
              this.selected = []
            },
            function (reason) {
              console.error('error: ' + reason.result.error.message)
            }
          )
        })

I've been Googling for a while with no luck, so any ideas would really be appreciated!

Enable custom session storage configuration

With the v1.0 refactoring, it would be relatively straightforward to enable applications to swap out the (default) local storage session storage with a custom implementation.

API key type

Hi,

I keep getting an error 400

message: "API key not valid. Please pass a valid API key."
status: "INVALID_ARGUMENT"

when calling this.$getGapiClient()

What kind of API Key should be generated to use with vue-gapi?

Thanks !

Output test coverage

Originally referenced in some Karma configuration; this would be nice to wire up at some point.

Help needed for Typescript

Firstly, thank you very much for this wrapper!

I am using Vue with typescript. When I tried to import VueGAPI from "vue-gapi", typescript wants me to provide a .d.ts file. For now, I created an empty .d.ts file to just pass the compiler. Can you please generate a .d.ts file for typescript users? Thank you!

Also, I am a little bit confused about how to use this:
this.$getGapiClient()
VScode gives me an error that $getGapiClient does not exist on type "App".

Thank you for helping me!

Generate documentation

The source code has some pretty solid documentation. We should consider leveraging that for some better, generated documentation with JSDoc or something of the sorts.

Access token cannot be accessed in latest chrome update

It seems that Google has changed the name of the property that holds the object with the access_token from Zi to uc.

So, in the following code snippet, authResult is undefined.

GoogleAuthService.prototype._setSession = function _setSession (response) {
  var profile = this.authInstance.currentUser.get().getBasicProfile();
  var authResult = response.Zi;
  this._setStorage(authResult, profile);
  this.authenticated = true;
};

Is anyone else experiencing this too?

TypeError: Cannot read property 'access_token' of null

Hi !

First of all, thanks for your great library!

Unfortunatly, when using this.$gapi.login() i receive the following error :

cb=gapi.loaded_0:181 Uncaught TypeError: Cannot read property 'access_token' of null
    at GoogleAuthService._setStorage (vue-gapi.common.js?15fd:83)
    at GoogleAuthService._setSession (vue-gapi.common.js?15fd:134)
    at eval (vue-gapi.common.js?15fd:155)
    at e.Sr (cb=gapi.loaded_0:192)
    at Lk (cb=gapi.loaded_0:195)
    at Gk (cb=gapi.loaded_0:195)
    at _.rk.xU (cb=gapi.loaded_0:195)
    at ok (cb=gapi.loaded_0:186)

Looking at the parent method, the response is almost empty.

image

The profile info is there :
image

If i call $gapi.login() a second time, everything works fine.
Also, if i refresh the page, i am logged in correctly

Thanks for your help,
Samuel

Error: localStorage is not defined

Every time I try to use import VueGAPI from 'vue-gapi I get the message: "localStorage is not defined".
Is this my wrong configuration or bug?

Improve documentation examples

The method-scoped Reference examples aren't very helpful and essentially just illustrate the method interface.

Perhaps we introduce a high-level examples / recipes section with some more comprehensive examples (that interact with multiple methods), i.e.

  • basic login / logout, detecting authenticated state
  • offline / refresh token stuff

Possibly unnecessary expiresAt function

We have a function that calculates the expiresAt Date from the expires_in seconds, althought according to the docs we already get the expires_at timestamp with the AuthResponse. So can we just use this property?

/**
* Return the expiration time of the user's auth session.
*
* @private
* @param {object} authResponse gapi.auth2.AuthResponse object
*
* @return {number}
*/
export function expiresAt(authResponse) {
return authResponse.expires_in * 1000 + Date.now()
}

Call for user update every 45min

Google expires the user token after one hour the recommended way to keep the user logged in is to refresh the token after 45min.

We should explore a way to keep the user logged in if the browser is still open. This will create a seamless user experience.

Safari Error

Is there any solutions to the error below, it occurs when I use safari.

my code
Screenshot 2021-01-18 at 1 09 12 PM

The error when I trigger the method above
Screenshot 2021-01-18 at 1 08 54 PM

Add version tags

The contributing guidelines state that this project follows semver but there are no commits annotated with tags. Can you annotate the commits with tags so Github recognizes them as releases and makes it easier to view the repository at a certain release? (I don't know whether it is possible to open a pull request for that)
Are there any plans to publish a new version to npm since there have been quite a few changes since v0.0.10?

Update Config on Fly

Hi,
I'm trying to use your Vue wrapper.
First I change your code to get the Google Config from the server, so i can change the config, save them and "re-init" each time my gapi.client.
It work.

Now I would like to understand how can I initialize the "googleAuthService.authInstance", because after calling the gapi.client.init it is always null!
what i'm doing wrong?
thanks

How check if user is Authenticated to redirect him.

@cedpoilly Hey mate,
How can I check is user is Authenticated? when I call this.$gapi.login() I have modal where I can select user etc. but after choose this I don't have promise to use .then(). So how can I check if user logged in correct to redirect him to some requiresAuth page.

Create event in Google Calendar after login

I want to run add event if user is logged in. If the user is not login, first user should get the auth screen and then add the event to the calendar. I tried using the bellow code,

                        syncWithGoogleCal(){
				if (!this.$gapi.isAuthenticated()) {
					this.$gapi.login()
				}else{
					this.$gapi.getGapiClient().then((gapi) => {
						// gapi.sheets.spreadsheet.get(...)
						var request = gapi.client.calendar.events.insert({
							"calendarId": 'primary",
							"conferenceDataVersion": 1,
							"resource": this.event
						});

						request.execute(function (event) {
							console.log(event);
							window.open(event.htmlLink, '_blank');
						});
					})
				}
			}

but its not working. How can I do this.?
Error in console: Uncaught (in promise) TypeError: Cannot read property 'events' of undefined
at eval (calendar.vue?3a51:259)

How to make gapi available to all component?

I have a lot of component make use of this plugin.

How can I make gapi available to all compoentns before app starts?

At the moment I have the following code in every component:

 this.$getGapiClient()
            .then(gapi => { ... })

Add inline component.

Having the pop up works and gets the job done with most cases, but devs should be able to select the login type weather it be inline, pop up etc....

Uncaught (in promise) TypeError: Cannot read property 'spreadsheets' of undefined

Everything works fine for authorization and initializing the API client. When it comes time to use the client for spreadsheets, that component is undefined.

My config json generated from Google Developer console:

{
    client_id: '3267693...obscured...jlnjs5kvji.apps.googleusercontent.com',
    project_id: 'evan-lycium-2098913',
    auth_uri: 'https://accounts.google.com/o/oauth2/auth',
    token_uri: 'https://accounts.google.com/o/oauth2/token',
    auth_provider_x509_cert_url: 'https://www.googleapis.com/oauth2/v1/certs',
    discoveryDocs: ['https://sheets.googleapis.com/$discovery/rest?version=v4'],
    scope: 'https://www.googleapis.com/auth/spreadsheets',
    client_secret: '331Q...obscured...3r2G',
    javascript_origins: ['http://localhost:8080']
  }

Code I am using in my methods block:

  methods: {
    getWeekdaySheet: function () {
      this.$getGapiClient().then(gapi => {
        console.log('got client, attempting batchGet with gapi.client.sheets:')
        gapi.client.sheets.spreadsheets.values.batchGet(params) // gapi.client.sheets is Undefined ????
          .then(function (response) {
            // TODO: Change code below to process the `response` object:
            console.log(response.result)
          }, function (reason) {
            console.error('error: ' + reason.result.error.message)
          })
      })
    }
  }

The gapi.client is initialized and authorized as I mentioned above. It is just that I cannot get the sheets api to get initialized along with it.

Support for Team Drives?

I wanted to create a new team drive with this wrapper but doesn't seem like this is possible yet?

isAuthenticated method will not work unless you refresh the page.

Since the isAuthenticated method works by using localStorage you can not call the method in a SPA app unless you have had the user refresh the page.

This results in a messy action of forcing users to refresh the page.

We should work towards finding a way to persists a isAuthenticated method.

valueInputOption not working

i'm trying to append data to a sheet. but i can set valueInputOption.
`this.$getGapiClient()
.then(gapi => {
gapi.client.sheets.spreadsheets.values.append({
spreadsheetId: this.sheetID,
range: 'sheet1',
'valueInputOption': "RAW",
resource: {values:[[1,2,3,4]]}
})
}).then((response) => {
console.log(response);

  })`

Load Gapi.js via Google CDN

Loading a static version of gapi.js seems to be causing some issues for this package right now - i.e., JS-blocking 404s.

Let me know if you want me to create a PR.

grantOfflineAccess

is there a way to call grantOfflineAccess to get the authorization code?

this.$gapi.isAuthenticated() is returning true even after logout

 onDriveLogoutClick: function() {
      this.$gapi.getGapiClient().then(gapi => {
        gapi.auth2
          .getAuthInstance()
          .signOut()
          .then(() => {
            this.gDriveAuthenticated = false;
            console.log("Drive logout successful");
          })
          .catch(err => {
            // eslint-disable-next-line no-console
            console.error("Login call failed: %s", err.message);
          });
      });
    }

Even after logout(above code)
console.log("isAuth:" + this.$gapi.isAuthenticated());

this is giving true

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.