最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Google Auth with Node.js using Typescript and Promise syntax - Stack Overflow

programmeradmin2浏览0评论

I am trying to implement google authentication using this tutorial:

but with Typescript and Promise syntax( these are the requirements) and I am getting this error:

This is the code:

import { HttpRequest, HttpResponse } from 'src/adapters/http';
import { OAuth2Client } from 'google-auth-library';
import { config } from './../../../config';

const client = new OAuth2Client(config.auth.google.id);

export const makeLoginUser = () => {
  return (httpRequest: HttpRequest, httpResponse: HttpResponse) => {
  new Promise(async (resolve, reject) => {
    const { tokenId } = httpRequest.body;
    console.log(tokenId);
    try {
      const ticket = await client.verifyIdToken({
        idToken: tokenId,
        audience: config.auth.google.id,
      });

      const { name, email, picture } = ticket.getPayload();

      resolve(httpResponse.status(200).send(email));
    } catch (error) {
      reject(httpResponse.status(429).send('Invalid request'));
    }
  });
};

};

I am trying to implement google authentication using this tutorial: https://blog.prototypr.io/how-to-build-google-login-into-a-react-app-and-node-express-api-821d049ee670

but with Typescript and Promise syntax( these are the requirements) and I am getting this error:

This is the code:

import { HttpRequest, HttpResponse } from 'src/adapters/http';
import { OAuth2Client } from 'google-auth-library';
import { config } from './../../../config';

const client = new OAuth2Client(config.auth.google.id);

export const makeLoginUser = () => {
  return (httpRequest: HttpRequest, httpResponse: HttpResponse) => {
  new Promise(async (resolve, reject) => {
    const { tokenId } = httpRequest.body;
    console.log(tokenId);
    try {
      const ticket = await client.verifyIdToken({
        idToken: tokenId,
        audience: config.auth.google.id,
      });

      const { name, email, picture } = ticket.getPayload();

      resolve(httpResponse.status(200).send(email));
    } catch (error) {
      reject(httpResponse.status(429).send('Invalid request'));
    }
  });
};

};

Share Improve this question edited Nov 8, 2022 at 15:10 Linda Lawton - DaImTo 118k39 gold badges225 silver badges501 bronze badges asked Jun 4, 2021 at 13:29 MarinescuMarinescu 4594 silver badges18 bronze badges 4
  • What's your question? What should happen if ticket.getPayload() returns undefined? Why do you destructure name and picture out of the result even though you only need email? – jonrsharpe Commented Jun 4, 2021 at 13:32
  • What's your question? -> For know I just want to verify the IdToken. What should happen if ticket.getPayload() returns undefined -> I will catch an error Why do you destructure name and picture out of the result even though you only need email? -> I will use them after, but for testing purposes I want to check if I can get de email of the user for now – Marinescu Commented Jun 4, 2021 at 13:38
  • OK, so what's the problem? Do you understand the messages the piler and ESLint are giving you? Have you researched their causes and possible solutions? – jonrsharpe Commented Jun 4, 2021 at 13:42
  • 'name' is an optional property of the tokenPayload type -> maybe use an intermediate step before assigning your return value to the variable 'name' googleapis.dev/nodejs/google-auth-library/5.8.0/interfaces/… – Godev Commented Jun 4, 2021 at 14:01
Add a ment  | 

1 Answer 1

Reset to default 4

I had same error and solved it like this:

import { Request, Response } from 'express'
import { OAuth2Client } from 'google-auth-library';
import UserModel from './../models/user';
var jwt = require('jsonwebtoken')

// @desc    Login with google
// @route   POST /api/user/google-login
// @access  Public

const client = new OAuth2Client(process.env.GOOGLE_CLIENT_ID)
export const signInWithGoogle = async (req: Request, res: Response) => {
  const { idToken } = req.body
  const ticket = await client.verifyIdToken({
    idToken,
    audience: process.env.GOOGLE_CLIENT_ID
  }).then((response) => {
    if (response.getPayload() && response.getPayload()?.email_verified) {
      const email = response.getPayload()?.email
      const name = response.getPayload()?.name
      
      UserModel.findOne({ email }).exec((err, user) => {
        if (user) {
          const token = jwt.sign({ _id: user._id }, process.env.JWT_SECRET, {
            expiresIn: "7d",
          })
          const { _id, email, name, role } = user
          return res.json({
            _id,
            name,
            email,
            role,
            token
          })
        } else {
          const password = `${email}${process.env.JWT_SECRET}`
          user = new UserModel({ name, email, password });
          user.save((err, data) => {
            if (err) {
              console.log("ERROR GOOGLE LOGIN ON USER SAVE", err)
              return res.status(400).json({
                error: "Google Login Failed"
              })
            }
            const token = jwt.sign(
              { _id: data._id },
              process.env.JWT_SECRET,
              {
                expiresIn: "7d"
              }
            )
            const { _id, email, name, role } = data
            return res.json({
              _id,
              name,
              email,
              role,
              token
            })
          })
        }
      })
    }
  })
}

发布评论

评论列表(0)

  1. 暂无评论