Skip to content

Instantly share code, notes, and snippets.

@aberba
Created November 21, 2023 21:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aberba/ce251adf626110512cec311a9c31cd52 to your computer and use it in GitHub Desktop.
Save aberba/ce251adf626110512cec311a9c31cd52 to your computer and use it in GitHub Desktop.
Google auth snippets
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