Git Product home page Git Product logo

vue-google-auth's Introduction

vue-google-auth

Handling Google sign-in and sign-out for Vue.js applications

Installation

npm install vue-google-auth

Initialization

import GoogleAuth from 'vue-google-auth'

Vue.use(GoogleAuth, { clientID: 'xxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com' })
Vue.googleAuth().load()

Ideally you shall place this in your app entry file, e.g. src/main.js

Usage - Sign-in

###(a) Handling Google sign-in, getting the one-time authorization code from Google

import Vue from 'vue'

Vue.googleAuth().signIn(function (authorizationCode) { 

  // things to do when sign-in succeeds
  
  // You can send the authorizationCode to your backend server for further processing, for example
  this.$http.post('http://your/backend/server', { code: authorizationCode, redirect_uri: 'postmessage' }).then(function (response) {
    if (response.body) {
      // ...
    }
  }, function (error) {
    console.log(error)
  })
  
}, function (error) {
  // things to do when sign-in fails
})

The authorizationCode that is being returned is the one-time code that you can send to your backend server, so that the server can exchange for its own access token and refresh token.

###(b) Alternatively, if you would like to directly get back the access_token and id_token

import Vue from 'vue'

// Just add in this line
Vue.googleAuth().directAccess()

Vue.googleAuth().signIn(function (googleUser) { 
  // things to do when sign-in succeeds
}, function (error) {
  // things to do when sign-in fails
})

The googleUser object that is being returned will be:

{
  "token_type": "Bearer",
  "access_token": "xxx",
  "scope": "xxx",
  "login_hint": "xxx",
  "expires_in": 3600,
  "id_token": "xxx",
  "session_state": {
    "extraQueryParams": {
      "authuser": "0"
    }
  },
  "first_issued_at": 1234567891011,
  "expires_at": 1234567891011,
  "idpId": "google"
}

Usage - Sign-out

Handling Google sign-out

import Vue from 'vue'

Vue.googleAuth().signOut(function () { 
  // things to do when sign-out succeeds
}, function (error) {
  // things to do when sign-out fails
})

Additional Help

Do refer to this sample login page HTML file.

If you are curious of how the entire Google sign-in flow works, please refer to the diagram below Google Sign-in Flow

vue-google-auth's People

Contributors

kirantambe avatar simmatrix 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

Watchers

 avatar  avatar

vue-google-auth's Issues

/auth/google content

As a newbie in VueJs and Google API, what should be the content on our proxy api on /auth/google ? (used on the onSignInSuccess)

I other words, how do we get the user info from the passed AuthorizationCode ?

Scopes are overwritten

config = Object.assign(options, { scope: 'profile email https://www.googleapis.com/auth/plus.login' })

This overwrites any user provided scopes

Changing to config = Object.assign({ scope: 'profile email https://www.googleapis.com/auth/plus.login' }, options) would preserve expected behavior since no one can add scopes anyway, but allow the optional parameter.

Firefox gapi undefined issue

when i tried login in firefox.it shows this error. why is that? works well on chrome...

TypeError: window.gapi is undefined

Console.log is lost with this module

Hi, I started to notice this weird behavior that when I open a page, the Console refreshes and the logs are lost, all of this makes it really hard to debug. The only way to avoid this is to enable the option "preserve logs" on Chrome.

I don't know if this is something that is wrong with Google or with this module. Something else I'm noticing is an iframe calling https://accounts.google.com/o/oauth2/postmessageRelay?parent= which results in the page never finished loading.

Blocked a frame with origin "http://localhost:8080" from accessing a cross-origin frame

I have imported the 3 lines into main.js

import GoogleAuth from 'vue-google-auth'
Vue.use(GoogleAuth, { client_id: 'myjibberish-xfewerwe.apps.googleusercontent.com' })
Vue.googleAuth().load()

And when I made a component based on sample.html

<template>  
  <div class="container container-table">
    <!-- Errors -->
    <div v-if=response class="text-red"><p>{{response}}</p></div>

    <!-- login Button -->
    <a id="signin-button" v-on:click="signIn">
      <i class="fa fa-google-plus-official fa-3x"></i>
      Sign in with Google
    </a>
  </div>

</template>


<script>
import axios from 'axios';
import Vue from 'vue'

	export default {
		name: 'webLogin',

  data: function () {
    return {
      section: 'Login',
      loading: '',
      response: ''
    }
  },
  	  computed: {
	  	BASE_URL () {
	  		return this.$store.state.BASE_URL;	
	  	}
	  },

methods: {
    signIn: function () {
      Vue.googleAuth().signIn(this.onSignInSuccess, this.onSignInError)
    },
    onSignInSuccess: function (authorizationCode) {
      console.log('sign in succesfull. code: ', authorizationCode)
      this.toggleLoading()
      this.resetResponse()
      this.$http.post( 'http://127.0.0.1:8090/web/auth', { code: authorizationCode, redirect_uri: 'postmessage' }).then(function (response) {
        if (response.body) {
          var data = response.body
          // Save to vuex
          var token = data.token
          this.$store.commit('SET_USER', data.user_data)
          this.$store.commit('SET_TOKEN', token)
          // Save to local storage as well 
          // ( or you can install the vuex-persistedstate plugin so that you won't have to do this step, only store to Vuex is sufficient )
          if (window.localStorage) {
            window.localStorage.setItem('user', JSON.stringify(data.user_data))
            window.localStorage.setItem('token', token)
          }
          // redirect to the dashboard
          this.$router.push({ name: 'home' })
        }
      }, function (response) {
        var data = response.body
        this.response = data.error
        console.log('BACKEND SERVER - SIGN-IN ERROR', data)
      })
    },
    onSignInError: function (error) {
      this.response = 'Failed to sign-in'
      console.log('GOOGLE SERVER - SIGN-IN ERROR', error)
    },
    toggleLoading: function () {
      this.loading = (this.loading === '') ? 'loading' : ''
    },
    resetResponse: function () {
      this.response = ''
    }
  }


}
	
 
</script>



<style>
</style>

But on component load I get this error in firefox:

uncaught exception: gapi.auth2.ExternallyVisibleError: Missing required parameter 'client_id'
I appreciate if you could provide a full working example. I really need google oauth2 for vue.js but could not find any one that actually works.

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

When I am trying to use this package in vue component. I am getting this error.
index.js:54 Uncaught (in promise) TypeError: Cannot read property 'getAuthInstance' of undefined at Object.signIn (index.js:54) at VueComponent.eval (VerifyGoogleAccount.vue?./node_modules/babel-loader/lib!./node_modules/vue-loader/lib/selector.js?type=script&index=0:53)

Missing required parameter 'client_id'

I have imported the 3 lines into main.js

import GoogleAuth from 'vue-google-auth'
Vue.use(GoogleAuth, { client_id: 'myjibberish-xfewerwe.apps.googleusercontent.com' })
Vue.googleAuth().load()

And when I made a component based on sample.html

<template>  
  <div class="container container-table">
    <!-- Errors -->
    <div v-if=response class="text-red"><p>{{response}}</p></div>

    <!-- login Button -->
    <a id="signin-button" v-on:click="signIn">
      <i class="fa fa-google-plus-official fa-3x"></i>
      Sign in with Google
    </a>
  </div>

</template>


<script>
import axios from 'axios';
import Vue from 'vue'

	export default {
		name: 'webLogin',

  data: function () {
    return {
      section: 'Login',
      loading: '',
      response: ''
    }
  },
  	  computed: {
	  	BASE_URL () {
	  		return this.$store.state.BASE_URL;	
	  	}
	  },

methods: {
    signIn: function () {
      Vue.googleAuth().signIn(this.onSignInSuccess, this.onSignInError)
    },
    onSignInSuccess: function (authorizationCode) {
      console.log('sign in succesfull. code: ', authorizationCode)
      this.toggleLoading()
      this.resetResponse()
      this.$http.post( 'http://127.0.0.1:8090/web/auth', { code: authorizationCode, redirect_uri: 'postmessage' }).then(function (response) {
        if (response.body) {
          var data = response.body
          // Save to vuex
          var token = data.token
          this.$store.commit('SET_USER', data.user_data)
          this.$store.commit('SET_TOKEN', token)
          // Save to local storage as well 
          // ( or you can install the vuex-persistedstate plugin so that you won't have to do this step, only store to Vuex is sufficient )
          if (window.localStorage) {
            window.localStorage.setItem('user', JSON.stringify(data.user_data))
            window.localStorage.setItem('token', token)
          }
          // redirect to the dashboard
          this.$router.push({ name: 'home' })
        }
      }, function (response) {
        var data = response.body
        this.response = data.error
        console.log('BACKEND SERVER - SIGN-IN ERROR', data)
      })
    },
    onSignInError: function (error) {
      this.response = 'Failed to sign-in'
      console.log('GOOGLE SERVER - SIGN-IN ERROR', error)
    },
    toggleLoading: function () {
      this.loading = (this.loading === '') ? 'loading' : ''
    },
    resetResponse: function () {
      this.response = ''
    }
  }


}
	
 
</script>



<style>
</style>

But on component load I get this error in firefox:

uncaught exception: gapi.auth2.ExternallyVisibleError: Missing required parameter 'client_id'
I appreciate if you could provide a full working example. I really need google oauth2 for vue.js but could not find any one that actually works.

Refresh token

Since the token is only valid for 1 hour it would be nice to include an option or perhaps by default reload expired tokens in exchange for fresh ones. I'm not entirely sure how to best implement this but this is what I'm testing out in my app:

setInterval(() => {
  window.gapi.auth2.getAuthInstance().currentUser.get().reloadAuthResponse().then((authRes) => {
    console.log('refreshing token')
     // app logic...
}, 3600000)

I'd be willing to take a look at it after I see that it works and open a PR later

Login to the last account instead of the new account

Hi, i have problem when login, i tried with 2 accounts, i tried login and then logout from account A, and re login with account B, but keep me logged in with account A.

here is my code, its quite similar with the sample code.

    openGoogleLoginDialog () {
        Vue.googleAuth().signIn(this.onSignInSuccess, this.onSignInError)
    },

   onSignInSuccess: function (authorizationCode) {
        let auth2 = gapi.auth2.getAuthInstance();
        let signedIn = auth2.isSignedIn.get()

        let user = auth2.currentUser.get().getBasicProfile();

        let data = {
            'provider': 'google',
            'id': user.getId(),
            'name': user.getName(),
            'email': user.getEmail(),
            'avatar': user.getImageUrl()
        }
        console.log(data)
        this.$store.dispatch('authenticate', data)
        .then((res) => {
            // console.log(res)
            this.$store.dispatch('loadNotifications')
            this.$router.push('/')
        })
        .catch((err) =>{
            console.log(err)
        })
    },

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.