Google Authentication using passport-google not working

957 views Asked by At

Here's the code i typed.

var passport = require("passport");
var GoogleStrategy = require("passport-google-oauth").OAuth2Strategy;

// Use the GoogleStrategy within Passport.
//   Strategies in Passport require a `verify` function, which accept
//   credentials (in this case, an accessToken, refreshToken, and Google
//   profile), and invoke a callback with a user object.
passport.use(
  new GoogleStrategy(
    {
      clientID: '28013134812-qc5lbogacg4cf42etiruqveskh8vaqgh.apps.googleusercontent.com',
      clientSecret: 'secret! i can't type secret here',
      callbackURL: "www.example.com.com/auth/google/callback",
    },
    function (accessToken, refreshToken, profile, done) {
      User.findOrCreate({ googleId: profile.id }, function (err, user) {
        return done(err, user);
      });
    }
  )
);

// GET /auth/google
//   Use passport.authenticate() as route middleware to authenticate the
//   request.  The first step in Google authentication will involve
//   redirecting the user to google.com.  After authorization, Google
//   will redirect the user back to this application at /auth/google/callback
app.get(
  "/auth/google",
  passport.authenticate("google", {
    scope: ["https://www.googleapis.com/auth/plus.login"],
  })
);

// GET /auth/google/callback
//   Use passport.authenticate() as route middleware to authenticate the
//   request.  If authentication fails, the user will be redirected back to the
//   login page.  Otherwise, the primary route function function will be called,
//   which, in this example, will redirect the user to the home page.
app.get(
  "/auth/google/callback",
  passport.authenticate("google", { failureRedirect: "/login" },
  function (req, res) {
    res.redirect("/");
  })
);

ReferenceError: User is not defined at Strategy._verify (C:\Users\hp\short.nner\server.js:64:7) at C:\Users\hp\short.nner\node_modules\passport-oauth2\lib\strategy.js:202:24 at C:\Users\hp\short.nner\node_modules\passport-google-oauth20\lib\strategy.js:122:5 at passBackControl (C:\Users\hp\short.nner\node_modules\oauth\lib\oauth2.js:134:9) at IncomingMessage. (C:\Users\hp\short.nner\node_modules\oauth\lib\oauth2.js:157:7) at IncomingMessage.emit (node:events:341:22) at endReadableNT (node:internal/streams/readable:1294:12) at processTicksAndRejections (node:internal/process/task_queues:80:21)

I copied the above code from passport docs. Does anyone know why I am getting this error? What actually is User here?

i think something's wrong with this code

function (accessToken, refreshToken, profile, done) {
      User.findOrCreate({ googleId: profile.id }, function (err, user) {
        return done(err, user);
      });
    }
1

There are 1 answers

0
Dingus45191 On BEST ANSWER

Just put correct callback URL here callbackURL: "http://localhost:3000.com/auth/google/callback", and define User. That's it