Currently, I find myself grappling with a Google Sign-in Authentication application that comprises a React frontend and an Express backend. The hurdle I currently face lies in the validation of tokens on the backend. The documentation for this process provides the following code snippet for validating the token:
const {OAuth2Client} = require('google-auth-library');
...
const client = new OAuth2Client(CLIENT_ID);
async function verify() {
const ticket = await client.verifyIdToken({
idToken: token,
audience: CLIENT_ID,
});
const payload = ticket.getPayload();
const userid = payload['sub'];
}
verify().catch(console.error);
In my own project, I have implemented this code as shown below:
//verify token
async function verify(token, client) {
const ticket = await client.verifyIdToken({
idToken: token,
audience: keys.google.clientID,
});
const payload = ticket.getPayload();
const userid = payload['sub'];
var message = '';
var cookie = {};
await User.find({email: email}, (error, user) => {
if(error) {
message = error;
} else if (user.length === 0) {
message = 'this user is not in the database';
} else {
message = 'this user is in the database';
const session = new Session({
email: email,
session_token: token
});
cookie = {
email: email,
session_token: token
};
session.save((error, session) => {
if (error) {
console.log(error);
} else {
console.log('session saved');
}
});
console.log(message);
}
});
return Promise.resolve(cookie);
}
//receive token id from frontend, verify it, and send session back in response
router.post('/google', (req, res) => {
const body = req.body.tokenID;
const client = new OAuth2Client(keys.google.clientID);
let cookie = verify(body, client).catch(console.error);
console.log('Cookie:' + cookie);
return res.send(cookie);
});
Despite all the async function execution, the return statement merely outputs an empty promise object. It appears I may be misusing async
and await
. If anyone could provide guidance on how to make the function wait for token verification and database updates before returning, I would greatly appreciate it.
Upon calling the route, my console displays the following information:
(I have anonymized personal information in the output for privacy, but the lines contain relevant data such as Gmail account information)
...
Cookie:[object Promise]
User ID: <GOOGLE ID>
Domain: <DOMAIN>
Email: <USER EMAIL>
This user is in the database
Session saved
Thank you for taking the time to read!