访问端点时未调用 Google 策略函数

问题描述 投票:0回答:0

我正在尝试对应用程序实施 Google 身份验证,并且我有登录和重定向端点。

这就是我在导入后在 server.js 中配置护照的方式

  server.use(passport.initialize())
  passport.use("google", googleStartegy)
  This is the Google Oauth File

import GoogleStartegy, { Strategy } from "passport-google-oauth20"
import UserSchema from "../../api/User/model.js"
import { createAcessToken } from "../jwtTools.js"

export const googleStartegy = new Strategy(
    {
      clientID: process.env.GOOGLE_ID,
      clientSecret: process.env.GOOGLE_SECRET,
      callbackURL: `${process.env.API_URL}/googleRedirect`,
    //   scope:["profile","email"]
    },
    async (_, __, profile, passportNext) => {
      // This function is executed when Google sends us a successfull response
      // Here we are going to receive some informations about the user from Google (scopes --> profile, email)

      try {
        const { email, given_name, family_name, sub } = profile._json
       console.log(email)
        // 1. Check if the user is already in db
        const author = await UserSchema.findOne({ email })
        if (author) {
          // 2. If he is there --> generate an accessToken (optionally also a refreshToken)
          const accessToken = await createAcessToken({ _id: author._id, role: author.role })
          console.log("PROFILE:", profile)
          // 2.1 Then we can go next (to /googleRedirect route handler function)
          passportNext(null, { accessToken })
        } else {
          // 3. If user is not in our db --> create that
          console.log("accessToken")
          const newUser = new UserSchema({
            firstName:given_name,
            lastName: family_name,
            email,
            googleId: sub,
          })
  
          const createdUser = await newUser.save()
  
          // 3.1 Then generate an accessToken (optionally also a refreshToken)
          const accessToken = await createAcessToken({ _id: createdUser._id, role: createdUser.role })
  
          // 3.2 Then we go next (to /googleRedirect route handler function)
          passportNext(null, { accessToken })
          
        }
      } catch (error) {
        // 4. In case of errors we gonna catch'em and handle them
        console.log(error)
        passportNext(error)
      
      }
    }
  )

我使用 jwt 为用户创建令牌但是

  1. 当我访问端点时,我在控制台中什么也得不到,数据库中也没有任何新内容。

这些是重定向和登录的路由

UserRouter.get("/googleLogin", passport.authenticate("google", { scope: ["profile", "email"] }))

UserRouter.get("/googleRedirect", passport.authenticate("google", { session: false }), (req, res, next) => {
  try {
    res.status(200).redirect(`${process.env.FE_URL}`)
  } catch (error) {
    next(error)
  }

})

我试图在任何地方添加 console.logs 更改 url 和在云应用程序中,但没有一个有效。

node.js express google-oauth passport.js
© www.soinside.com 2019 - 2024. All rights reserved.