Created
November 21, 2023 21:01
-
-
Save aberba/ce251adf626110512cec311a9c31cd52 to your computer and use it in GitHub Desktop.
Google auth snippets
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 { OAuth2Client } = require("google-auth-library"); | |
var client = new OAuth2Client(process.env.GOOGLE_CLIENT_ID, "", ""); | |
async function getGoogleUser(token) { | |
try { | |
const login = await client.verifyIdToken({ | |
idToken: token, | |
audience: process.env.GOOGLE_CLIENT_ID, | |
}); | |
var payload = login.getPayload(); | |
// check if the jwt is issued for our client | |
var audience = payload.aud; | |
if (audience !== process.env.GOOGLE_CLIENT_ID) { | |
return { | |
isSuccess: false, | |
message: "Token provided seems malicious.", | |
}; | |
} | |
return { | |
isSuccess: true, | |
metaData: { | |
name: payload["name"], //profile name | |
email: payload["email"], | |
googleId: payload["sub"], //google id | |
profilePictureURL: payload["picture"], //profile pic | |
isEmailVerified: payload["email_verified"], | |
}, | |
}; | |
} catch (error) { | |
debug(error); | |
return { | |
isSuccess: false, | |
message: | |
"Failed to authenticate with your Google account. Please make sure you provide valid credentials.", | |
}; | |
} | |
} | |
/* | |
* In your route | |
*****************************************/ | |
// 1. get google user with id_token | |
// 2. check user match in db | |
// 3. if success, create token and send | |
let userAccount = await UserService.findOneByIdentityCredentials({ | |
data, | |
provider, | |
}); | |
const tokenString = await createTokenString({ | |
user: { id: userAccount._id }, | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment