I can’t seem to pass the challenge https://www.freecodecamp.org/learn/quality-assurance/advanced-node-and-express/implementation-of-social-authentication-iii
I believe my code is okay. I have tested the login manually and it’s working. My code so far
routes.js
const passport = require('passport');
function ensureAuthenticated(req, res, next) {
if (req.isAuthenticated()) {
return next();
}
res.redirect('/');
};
module.exports = function(app, userCollection) {
app.route('/').get((req, res) => {
res.render(__dirname + '/views/pug', {
title: 'Connected to Database',
message: 'Please login',
showLogin: true,
showRegistration: true,
showSocialAuth: true,
});
});
app.route('/register')
.post((req, res, next) => {
userCollection.findOne({ username: req.body.username }, function(err, user) {
if (err) {
next(err);
} else if (user) {
res.redirect('/');
} else {
const hash = bcrypt.hashSync(req.body.password, 12);
userCollection.insertOne({
username: req.body.username,
password: hash
},
(err, doc) => {
if (err) {
res.redirect('/');
} else {
// The inserted document is held within
// the ops property of the doc
next(null, doc.ops[0]);
}
}
)
}
})
},
passport.authenticate('local', { failureRedirect: '/' }),
(req, res, next) => {
res.redirect('/profile');
}
);
app.post('/login', passport.authenticate('local', { failureRedirect: '/' }), function(req, res) {
res.redirect('/profile');
});
app.get('/auth/github',
passport.authenticate('github'), function(req, res) {
redirect('/profile');
});
app.get('/auth/github/callback',passport.authenticate('github', { failureRedirect: '/' }), function(req, res) {
res.redirect('/profile');
});
app.route('/profile')
.get(ensureAuthenticated, (req,res) => {
res.render(__dirname + '/views/pug/profile', {
username: req.user.username
});
});
app.route('/logout')
.get((req, res) => {
req.logout();
res.redirect('/');
});
/// not found route
app.use((req, res, next) => {
res.status(404)
.type('text')
.send('Not Found');
});
}
auth.js
const session = require('express-session');
const passport = require('passport');
const LocalStrategy = require('passport-local');
const GitHubStrategy = require('passport-github').Strategy;
const bcrypt = require('bcrypt');
const { ObjectID } = require('mongodb');
module.exports = function(app, userCollection) {
app.use(session({
secret: process.env.SESSION_SECRET,
resave: true,
saveUninitialized: true,
cookie: { secure: false }
}));
app.use(passport.initialize());
app.use(passport.session());
passport.use(new GitHubStrategy({
clientID: process.env.GITHUB_CLIENT_ID,
clientSecret: process.env.GITHUB_CLIENT_SECRET,
callbackURL: "https://2a1e-41-174-110-247.eu.ngrok.io/auth/github/callback"
},
function(accessToken, refreshToken, profile, done) {
console.log(profile);
userCollection.findOneAndModify(
{ id: profile.id },
{
$setOnInsert: {
id: profile.id,
name: profile.displayName || 'J. Doe',
photo: profile.photos[0].value || '',
username: profile.username || 'JDoe',
email: Array.isArray(profile.emails)
? 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) => {
console.log('====================================================================================')
console.log(doc.value);
console.log(err);
console.log('====================================================================================')
return done(err, doc.value);
}
);
// userCollection.findOne({ githubId: profile.id }, function (err, user) {
// if (err) return done(err);
// if (!user) {
// userCollection.insertOne({
// githubId: profile.id,
// username: profile.username
// }, function(err, user) {
// if (err)
// return done(err);
// done(null, user);
// });
// } else {
// done(null, user);
// }
// });
}
));
passport.use(new LocalStrategy(
function(username, password, done) {
userCollection.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); }
const credentialsAreValid = bcrypt.compareSync(password, user.password);
if (!credentialsAreValid) {
return done(null, false);
}
return done(null, user);
});
}
));
passport.serializeUser((user, done) => {
console.log(user);
done(null, user._id);
});
passport.deserializeUser((id, done) => {
userCollection.findOne({ _id: new ObjectID(id) }, (err, doc) => {
done(null, doc);
});
});
}
server.js
'use strict';
console.clear();
require('dotenv').config();
const express = require('express');
const myDB = require('./connection');
const fccTesting = require('./freeCodeCamp/fcctesting.js');
const routes = require('./routes');
const auth = require('./auth');
const app = express();
fccTesting(app); //For FCC testing purposes
app.set('view engine', 'pug');
function getDbClient() {
return new Promise(async (resolve, reject) => {
try {
await myDB(resolve);
} catch (err) {
reject(err);
}
});
}
(async () => {
// setup database
const client = await getDbClient();
const userCollection = await client.db('database').collection('users');
// middlewares
app.use('/public', express.static(process.cwd() + '/public'));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// auth
auth(app, userCollection);
// routes
routes(app, userCollection);
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log('Listening on port ' + PORT);
});
})();
Your browser information:
User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36
Challenge: Implementation of Social Authentication III
Link to the challenge: