Skip to content

Instantly share code, notes, and snippets.

@JosephLivengood
Last active September 6, 2020 12:33
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JosephLivengood/28ea2cae7e1dc6a53d7f0c42d987313b to your computer and use it in GitHub Desktop.
Save JosephLivengood/28ea2cae7e1dc6a53d7f0c42d987313b to your computer and use it in GitHub Desktop.
FCC Advanced Node and Express Social Auth Checkpoint 1
'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 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, (err, db) => {
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
*/
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);
});
}});
@djasuncion
Copy link

i'm confused about this, is it a testing error?

//will not pass test
app.get(
  '/auth/github/callback',
  passport.authenticate('github', { failureRedirect: '/' }),
  (req, res) => {
    res.redirect('/profile')
  }
)

//passes test
app
  .route('/auth/github/callback')
  .get(
    passport.authenticate('github', { failureRedirect: '/' }),
    (req, res) => {
      res.redirect('/profile')
    }
  )

@huyN1349
Copy link

huyN1349 commented Apr 8, 2020

The code above may pass the test but the application doesn't work. You need to have the package passport-github installed and the strategy configured.

const GitHubStrategy = require('passport-github').Strategy;
    /*
    *  ADD YOUR CODE BELOW
    */
  
    //Configure Github Strategy 
    passport.use(new GitHubStrategy({
      clientID: process.env.GITHUB_CLIENT_ID,
      clientSecret: process.env.GITHUB_CLIENT_SECRET,
      callbackURL: "https://maze-rainy-curio.glitch.me/auth/github/callback"
      },
      function(accessToken, refreshToken, profile, done) {
          return done(null, profile);
      }
    ));
  
    app.route('/auth/github')
      .get(passport.authenticate('github')),
  
    app.route('/auth/github/callback')
      .get(passport.authenticate('github', { failureRedirect: '/' }),
      function(req,res){
        res.redirect("/profile")
    });

    /*
    *  ADD YOUR CODE ABOVE
    */

@djasuncion
Copy link

The code above may pass the test but the application doesn't work. You need to have the package passport-github installed and the strategy configured.

const GitHubStrategy = require('passport-github').Strategy;
    /*
    *  ADD YOUR CODE BELOW
    */
  
    //Configure Github Strategy 
    passport.use(new GitHubStrategy({
      clientID: process.env.GITHUB_CLIENT_ID,
      clientSecret: process.env.GITHUB_CLIENT_SECRET,
      callbackURL: "https://maze-rainy-curio.glitch.me/auth/github/callback"
      },
      function(accessToken, refreshToken, profile, done) {
          return done(null, profile);
      }
    ));
  
    app.route('/auth/github')
      .get(passport.authenticate('github')),
  
    app.route('/auth/github/callback')
      .get(passport.authenticate('github', { failureRedirect: '/' }),
      function(req,res){
        res.redirect("/profile")
    });

    /*
    *  ADD YOUR CODE ABOVE
    */

Hi, is this a reply to my comment? mine works, actually...

@huyN1349
Copy link

huyN1349 commented Apr 8, 2020

@djma777: I was referring to the author's code. I can't see what your codes look like. You may have set up the github strategy correctly.

@magnusbarata
Copy link

magnusbarata commented Apr 20, 2020

If you get the "TypeError: Cannot read property 'value' of null at db.collection.findAndModify" after checkpoint 3, don't forget

mongo.connect(process.env.MONGO_URI, (err, client) => {
   let db = client.db("yourproject");

Also, if you are using mongodb ver 3.0 or later, you can try this:

const mongo = require('mongodb').MongoClient;
const client = new mongo(process.env.MONGO_URI, {useNewUrlParser: true, useUnifiedTopology: true});
client.connect(err => {
    let db = client.db('yourdb');

@Walf-dev
Copy link

Walf-dev commented Aug 2, 2020

The tester is very sensitive to this identation:

app.route('/auth/github/callback') .get(passport.authenticate('github', { failureRedirect: '/' }), (req,res) => { res.redirect('/profile'); });

Copy and paste the following without backsticks

@ganeshh123
Copy link

ganeshh123 commented Aug 7, 2020

My Solution - works for now

Firstly, create environment variables for a Session Secret string and your database password

Create a variable for your database URI, concatenating your password from the environment variables, and filling in your database name, and use this in your connection method.

let uri =
  "mongodb+srv://user1:" +
  process.env.PW +
  "@freecodecamp.b0myq.mongodb.net/advancednode?retryWrites=true&w=majority";
mongo.connect(uri, (err, db) => {

Get a some Github Oauth Credentials and store them in your environment variables.

Create a route for the login link (/auth/github), and inside call the authenticate() method on passport with the strategy name of 'github'.

Create a route for the callback url (/auth/github/callback) and inside, run the authenticate() method on passport with the same strategy name. This time, set up a failureRedirect option to back to the login page. As a second middleware, call the redirect() method on the response to the '/profile' route.

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

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

Make sure you don't format your code on Glitch, the lines must be like this!

@piouson
Copy link

piouson commented Sep 6, 2020

opened #39533

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment