Skip to content

Instantly share code, notes, and snippets.

@ShaunSHamilton
Last active October 17, 2022 13:54
Show Gist options
  • Save ShaunSHamilton/544b09be457316c39634ad4fd876d694 to your computer and use it in GitHub Desktop.
Save ShaunSHamilton/544b09be457316c39634ad4fd876d694 to your computer and use it in GitHub Desktop.
Advanced Node and Express - Implementation of Social Authentication
const passport = require('passport');
const bcrypt = require('bcrypt');
module.exports = function (app, myDataBase) {
app.route('/').get((req, res) => {
res.render('index', {
title: 'Connected to Database',
message: 'Please log in',
showLogin: true,
showRegistration: true,
showSocialAuth: true
});
});
app.route('/login').post(passport.authenticate('local', { failureRedirect: '/' }), (req, res) => {
res.redirect('/profile');
});
app.route('/profile').get(ensureAuthenticated, (req,res) => {
res.render('profile', { username: req.user.username });
});
app.route('/logout').get((req, res) => {
req.logout();
res.redirect('/');
});
app.route('/register').post((req, res, next) => {
const hash = bcrypt.hashSync(req.body.password, 12);
myDataBase.findOne({ username: req.body.username }, (err, user) => {
if (err) {
next(err);
} else if (user) {
res.redirect('/');
} else {
myDataBase.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.route('/auth/github').get(passport.authenticate('github'));
app.route('/auth/github/callback').get(passport.authenticate('github', { failureRedirect: '/' }), (req, res) => {
res.redirect('/profile');
})
app.use((req, res, next) => {
res.status(404)
.type('text')
.send('Not Found');
});
}
function ensureAuthenticated(req, res, next) {
if (req.isAuthenticated()) {
return next();
}
res.redirect('/');
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment