How can I relate a google user with a document in my collection?

Viewed 26

I have an Express and Mongo blog app. I implemented the google authentication, but I don't know how to save the user id along with the post that the user creates.

This are the google settings:

const {OAuth2Client} = require('google-auth-library');
const client = new OAuth2Client(process.env.GOOGLE_CLIENT_ID);
const googleVerify = async( idToken = '' ) => {

    const ticket = await client.verifyIdToken({
        idToken,
        audience: process.env.GOOGLE_CLIENT_ID
    });
  
    const { name, 
            picture: img, 
            email,
            sub: id
    } = ticket.getPayload();

    return { name, img, email, id };
  
}


const googleSignIn = async(req, res = response) => {

    try {
        let googleUser = await googleVerify(req.body.id_token);
        console.log(googleUser);
        // console.log(googleUser);
    } catch (error) {
        res.status(400).json({
            msg: 'Token de google no valido'
        })
    }

}

And this is the post route for an article:

router.post('/', upload.single('image'), async (req, res) => {
    let body = req.body;

    const article = new Article({
        title: body.title,
        description: body.description,
        markdown: body.markdown,
        img: req.file.filename
    });

    try {
        await article.save();
    } catch (error) {
        console.log(error);
        res.render('new', {article: article});
    } finally {
        res.redirect(`/articles/${article.id}`);
    }

});

How can I access the logged user from that article route?

Thank you!!

1 Answers

One way to get get your logged-in user from your express post route would be to call your googleVerify() function from within the route like this

router.post('/', upload.single('image'), async (req, res) => {
    ...

    const googleUser = await googleVerify(req.body.id_token);
    // Do stuff with your googleUser here

    ...
});

The above should work just fine, provided the client is sending the id_token during the post request, and if your googleVerify() function is defined in another file then you might need to export and import it here to use.

Another way would be to use the googleSignIn function as a middleware

router.post('/', googleSignIn, upload.single('image'), async (req, res) => {
    ...
    let body = req.body;
    // you should have access to googleUser like this
    // body.googleUser
    ...
});

Then refactor your googleSignIn function to take a next function like this

const googleSignIn = async(req, res, next) => {

    try {
        let googleUser = await googleVerify(req.body.id_token);
        console.log(googleUser);

        req.body.googleUser = googleUser; // set user to the request body
        next(); // Moves to next middleware

    } catch (error) {
        res.status(400).json({
            msg: 'Token de google no valido'
        })
    }

}
Related