Advanced Node and Express - How to Use Passport Strategies, challenge 7

hi, I cant’ find the error, I get (Error: Unknown authentication strategy “local”)

Your code so far
“use strict”;

const express = require(“express”);
const fccTesting = require("./freeCodeCamp/fcctesting.js");
const session =require(‘express-session’)
const passport = require(‘passport’)
const db = require(‘mongodb’)
const ObjectID =db.ObjectID
const mongo = require(‘mongodb’).MongoClient;
const LocalStrategy = require(‘passport-local’);
const app = express();
fccTesting(app); //For FCC testing purposes
app.use("/public", express.static(process.cwd() + “/public”));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

app.use(session({
secret: process.env.SESSION_SECRET,
resave: true,
saveUninitialized: true,
}));
app.use(passport.initialize());
app.use(passport.session ());

mongo.connect(process.env.DATABASE, (err, db) => {
if(err) {
console.log('Database error: ’ + err);
} else {
console.log(‘Successful database connection’);

passport.use(new LocalStrategy(

function(username, password, done) {
db.collection(‘users’).findOne({ username: username }, function (err, user) {
console.log(‘User ‘+ username +’ attempted to log in.’);
if (err) { return done(err); }
if (!user) { return done(null, false); }
if (password !== user.password) { return done(null, false); }
return done(null, user);
});
}
));
//serialization and app.listen
passport.serializeUser((user, done) => {
done(null, user._id)
});
passport.deserializeUser((id, done) => {
db.collection(‘users’).findOne(
{_id: new ObjectID(id)},
(err, doc) => {
done(null, doc);
}
);
});
}
});

app.set(‘view engine’, ‘pug’)
app.set(‘views’, ‘./views/pug’)
app.route("/").get((req, res) => {
//Change the response to render the Pug template
res.render(process.cwd() + ‘/views/pug/index’, {title: ‘Hello’, message: ‘Please login’, showLogin:true, showRegistration:true})
});

app.route(’/login’)
.post( passport.authenticate(‘local’, { failureRedirect:’/’ }) , function(req, res){
res.redirect(’/profile’)
});
app.route(’/profile’)
.get( function(req, res){
res.render(process.cwd() + ‘/views/pug/profile’)
});

app.listen(process.env.PORT || 3000, () => {
console.log("Listening on port " + process.env.PORT);
});

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.125 Safari/537.36.

Challenge: Advanced Node and Express - How to Use Passport Strategies

Link to the challenge:

Welcome, fernandez.

You should have your routing and serialisation logic within your database connection callback.

In general, the routes come first, then the serialisation logic after.

Hope this helps

It’s a bit difficult to read without proper formatting. So instead I’ll copy my index.js content so you can compare it with yours.

"use strict";

const express = require("express");
const bodyParser = require("body-parser");
const fccTesting = require("./freeCodeCamp/fcctesting.js");
const session = require("express-session");
const mongo = require("mongodb").MongoClient;
const passport = require("passport");
const GitHubStrategy = require("passport-github").Strategy;

const app = express();

fccTesting(app); //For FCC testing purposes

app.use("/public", express.static(process.cwd() + "/public"));
app.use(bodyParser.json());
app.use(
  bodyParser.urlencoded({
    extended: true
  })
);

app.set("view engine", "pug");

mongo.connect(
  process.env.DATABASE,
  {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    useFindAndModify: false
  },
  (err, client) => {
    var db = client.db("fcc_test_users");
    if (err) {
      console.log("Database error: " + err);
    } else {
      console.log("Successful database connection");

      app.use(
        session({
          secret: process.env.SESSION_SECRET,
          resave: true,
          saveUninitialized: true
        })
      );
      app.use(passport.initialize());
      app.use(passport.session());

      function ensureAuthenticated(req, res, next) {
        if (req.isAuthenticated()) {
          return next();
        }
        res.redirect("/");
      }

      passport.serializeUser((user, done) => {
        done(null, user.id);
      });

      passport.deserializeUser((id, done) => {
        db.collection("socialusers").findOne(
          {
            id: id
          },
          (err, doc) => {
            done(null, doc);
          }
        );
      });

      /*
       *  ADD YOUR CODE BELOW
       */
      passport.use(
        new GitHubStrategy(
          {
            clientID: process.env.GITHUB_CLIENT_ID,
            clientSecret: process.env.GITHUB_CLIENT_SECRET,
            callbackURL:
              "https://sharkantropo-socialauth-boilerplate.glitch.me/auth/github/callback"
          },
          function(accessToken, refreshToken, profile, cb) {
            console.log(profile);
            //Database logic here with callback containing our user object
            db.collection("socialusers").findAndModify(
              { id: profile.id },
              {},
              {
                $setOnInsert: {
                  id: profile.id,
                  name: profile.displayName || "John Doe",
                  photo: profile.photos[0].value || "",
                  email: profile.emails[0].value || "No public email",
                  created_on: new Date(),
                  provider: profile.provider || ""
                },
                $set: {
                  last_login: new Date()
                },
                $inc: {
                  login_count: 1
                }
              },
              { upsert: true, new: true },
              (err, doc) => {
                return cb(null, doc.value);
              }
            );
          }
        )
      );

      app.route("/auth/github").get(passport.authenticate("github"));

      app
        .route("/auth/github/callback")
        .get(
          passport.authenticate("github", { failureRedirect: "/" }),
          (req, res) => {
            res.redirect("/profile");
          }
        );
      /*
       *  ADD YOUR CODE ABOVE
       */

      app.route("/").get((req, res) => {
        res.render(process.cwd() + "/views/pug/index");
      });

      app.route("/profile").get(ensureAuthenticated, (req, res) => {
        res.render(process.cwd() + "/views/pug/profile", {
          user: req.user
        });
      });

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

      app.use((req, res, next) => {
        res
          .status(404)
          .type("text")
          .send("Not Found");
      });

      app.listen(process.env.PORT || 3000, () => {
        console.log("Listening on port " + process.env.PORT);
      });
    }
  }
);