Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

passport: req.isAuthenticated() is not a function and req.user is not being set by passport

I’m creating a web application using the MERN stack for which I want to implement google OAuth and session and I’m using ‘express-session’ and ‘passport.js’ for this. Everything seems to be working as expected but I’m getting an error: req.isAuthenticated isn't function. Also, the value of req.user is "undefined" but, the cookie is being generated and successfully stored in MongoDB. I’m new to node and passport so I’m not able to figure out the problem. Also, solutions to previously asked questions on this same error aren’t working for me.

This is the error

(node:10481) UnhandledPromiseRejectionWarning: TypeError: req.isAuthenticated is not a function
    at addYear (/media/test/DATA/Dev/full-stack/projects/budget-app-backend/controllers/years.js:15:18)
    at Layer.handle [as handle_request] (/media/test/DATA/Dev/full-stack/projects/budget-app-backend/node_modules/express/lib/router/layer.js:95:5)
    at next (/media/test/DATA/Dev/full-stack/projects/budget-app-backend/node_modules/express/lib/router/route.js:137:13)
    at Route.dispatch (/media/test/DATA/Dev/full-stack/projects/budget-app-backend/node_modules/express/lib/router/route.js:112:3)
    at Layer.handle [as handle_request] (/media/test/DATA/Dev/full-stack/projects/budget-app-backend/node_modules/express/lib/router/layer.js:95:5)
    at /media/test/DATA/Dev/full-stack/projects/budget-app-backend/node_modules/express/lib/router/index.js:281:22
    at Function.process_params (/media/test/DATA/Dev/full-stack/projects/budget-app-backend/node_modules/express/lib/router/index.js:341:12)
    at next (/media/test/DATA/Dev/full-stack/projects/budget-app-backend/node_modules/express/lib/router/index.js:275:10)
    at Function.handle (/media/test/DATA/Dev/full-stack/projects/budget-app-backend/node_modules/express/lib/router/index.js:174:3)
    at router (/media/test/DATA/Dev/full-stack/projects/budget-app-backend/node_modules/express/lib/router/index.js:47:12)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:10481) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:10481) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

I’m also adding the code for reference.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

code in server.js

const dotenv = require("dotenv");
dotenv.config();
const express = require("express");
const cors = require("cors");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const passport = require("passport");
const session = require("express-session");
const MongoStore = require("connect-mongo");
const authRouter = require("./routes/auth");
const Info = require("./models/Info");
const Transaction = require("./models/Transactions");
const recordsRouter = require("./routes/recordsRouter");
const { User, userSchema } = require("./models/Users");
const GoogleStrategy = require("passport-google-oauth20").Strategy;
const startDB = require("./models/db");

const app = express();
const PORT = process.env.PORT || 8000;

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(
    cors({
        origin: "http://localhost:3000",
        methods: "GET,POST,PUT,DELETE",
        credentials: true,
    })
);
app.use(
    session({
        secret: "some random string",
        resave: false,
        saveUninitialized: false,
        store: MongoStore.create({
            mongoUrl: "mongodb://0.0.0.0:37017/budgetDB",
        }),
    })
);

startDB();

app.use("/auth", authRouter);
app.use("/dashboard", recordsRouter);

app.use(passport.initialize());
app.use(passport.session());

require("./passport")(passport);

app.listen(PORT, () => {
    console.log(`Server started listening on port ${PORT}.....`);
});

code in passport.js

const { User } = require("./models/Users");
const GoogleStrategy = require("passport-google-oauth20").Strategy;

module.exports = function (passport) {
    passport.serializeUser((user, done) => {
        console.log(`From passport.js serializeUser: ${user}`);
        return done(null, user.id);
    });

    passport.deserializeUser((id, done) => {
        User.findById(id, (err, user) => {
            done(err, user);
        });
    });

    passport.use(
        new GoogleStrategy(
            {
                clientID: process.env.CLIENT_ID,
                clientSecret: process.env.CLIENT_SECRET,
                callbackURL: "http://localhost:8000/auth/google/callback",
                userProfileURL: "https://www.googleapis.com/oauth2/v3/userinfo",
            },

            async (accessToken, refreshToken, profile, done) => {
                const newUser = new User({
                    name: profile.displayName,
                    googleId: profile.id,
                });

                try {
                    const user = await User.findOne({ googleId: profile.id });
                    if (!user) {
                        user = await User.create(newUser);
                    }
                    return done(null, user);
                } catch (err) {
                    console.log(`Error From 'passport.js': ${err}`);
                    return done(err);
                }
            }
        )
    );
};

code in auth.js

const router = require("express").Router();
const passport = require("passport");

const CLIENT_URL = "http://localhost:3000";

router.get("/login/failed", (req, res) => {
    console.log(res);
    res.status(401).json({
        message: "login failed",
    });
});

router.get("/logout", (req, res) => {
    req.logout();
    res.redirect(CLIENT_URL);
});

router.get("/google", passport.authenticate("google", { scope: ["profile"] }));

router.get(
    "/google/callback",
    passport.authenticate("google", {
        failureRedirect: "/login/failed",
        successRedirect: CLIENT_URL + "/Dashboard",
    })
);

module.exports = router;

code in User model

const mongoose = require("mongoose");

const userSchema = new mongoose.Schema({
    name: String,
    googleId: String,
});

const User = mongoose.model("User", userSchema);

module.exports = { User, userSchema };

>Solution :

Middlewares orders is important. Put the .use(passport...) before the .use(router...)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading