Last active
February 1, 2018 11:30
-
-
Save Spyna/a70a19e313d3eb666b3857485e63161c to your computer and use it in GitHub Desktop.
google-auth-library token_id check
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const credentials = require( './credentials.json' ) | |
const GOOGLE_CLIENT_ID = credentials.google.client_id; | |
const { OAuth2Client } = require( 'google-auth-library' ); | |
var client = new OAuth2Client( GOOGLE_CLIENT_ID, '', '' ); | |
//return a promise with user informations | |
module.exports.getGoogleUser = ( code ) => { | |
//verify the token using google client | |
return client.verifyIdToken( { idToken: code, audience: GOOGLE_CLIENT_ID } ) | |
.then( login => { | |
//if verification is ok, google returns a jwt | |
var payload = login.getPayload(); | |
var userid = payload['sub']; | |
//check if the jwt is issued for our client | |
var audience = payload.aud; | |
if ( audience !== GOOGLE_CLIENT_ID ) { | |
throw new Error( "error while authenticating google user: audience mismatch: wanted [" + GOOGLE_CLIENT_ID + "] but was [" + audience + "]" ) | |
} | |
//promise the creation of a user | |
return { | |
name: payload['name'], //profile name | |
pic: payload['picture'], //profile pic | |
id: payload['sub'], //google id | |
email_verified: payload['email_verified'], | |
email: payload['email'] | |
} | |
} ) | |
.then( user => { return user; } ) | |
.catch( err => { | |
//throw an error if something gos wrong | |
throw new Error( "error while authenticating google user: " + JSON.stringify( err ) ); | |
} ) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment