vue-google-auth
Version:
Handling Google sign-in and sign-out
90 lines (79 loc) • 2.74 kB
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>
/** -----------------------------------------------------------------------------------------------------------
* You would first need to place these 3 lines of code in your APP ENTRY file, e.g. src/main.js
*
* import GoogleAuth from 'vue-google-auth'
* Vue.use(GoogleAuth, { client_id: 'xxxxxxxx-xxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com' })
* Vue.googleAuth().load()
*
* -----------------------------------------------------------------------------------------------------------
*/
import Vue from 'vue'
module.exports = {
name: 'Login',
data: function (router) {
return {
section: 'Login',
loading: '',
response: ''
}
},
methods: {
signIn: function () {
Vue.googleAuth().signIn(this.onSignInSuccess, this.onSignInError)
},
onSignInSuccess: function (authorizationCode) {
this.toggleLoading()
this.resetResponse()
this.$http.post('http://your-backend-server.com/auth/google', { code: authorizationCode, redirect_uri: 'postmessage' }).then(function (response) {
if (response.body) {
var data = response.body
// Save to vuex
this.$store.commit('SET_USER', data.user_data)
var token = 'Bearer ' + data.token
this.$store.commit('SET_TOKEN', token)
// Save to local storage as well
if (window.localStorage) {
window.localStorage.setItem('user', JSON.stringify(data.user_data))
window.localStorage.setItem('token', token)
}
// redirect to the dashboard
this.$router.replace('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>
/**
* ----------------------------------------------------
* Styling? It's time to show your designing skills!
* ----------------------------------------------------
*/
</style>