I tried using the forums and I’ve completed 3 out of the 5 challenges. The only two that won’t pass are registering should work and login should work. Any suggestions I could try?
mongo.connect(process.env.DATABASE, (err, db) => {
if(err) {
console.log('Database error: ' + err);
} else {
console.log('Successful database connection');
//serialization and app.listen
}
});
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);
});
}
));
app.set('view engine', 'pug');
function ensureAuthenticated(req, res, next) {
if (req.isAuthenticated()) {
return next();
}
res.redirect('/');
};
app.route("/").get((req, res) => {
//Change the response to render the Pug template
res.render(process.cwd() + '/views/pug/index.pug', {title: "Home Page", message: 'Please login', showLogin: true, showRegistration: true});
});
app.route('/login')
.post(passport.authenticate('local', { failureRedirect: '/' }),(req,res) => {
res.redirect('/profile');
console.log(`User ${req.user} attempted to log in.`);
res.redirect('/');
});
app.route('/profile')
.get(ensureAuthenticated,(req,res) => {
res.render(process.cwd() + '/views/pug/profile.pug'+ { username: req.user.username });
});
app.route('/register')
.post((req, res, next) => {
db.collection('users').findOne({ username: req.body.username }, function(err, user) {
if (err) {
next(err);
} else if (user) {
res.redirect('/');
} else {
db.collection('users').insertOne({
username: req.body.username,
password: req.body.password
},
(err, doc) => {
if (err) {
res.redirect('/');
} else {
next(null, user);
}
}
)
}
})
},
passport.authenticate('local', { failureRedirect: '/' }),
(req, res, next) => {
res.redirect('/profile');
}
);
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);
});
Here’s my project page: