javascriptCopy code
const express = require('express');
const session = require('express-session');
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
javascriptCopy code
const app = express();
javascriptCopy code
mongoose.connect('mongodb://localhost:27017/simple_db', { useNewUrlParser: true, useUnifiedTopology: true });
javascriptCopy code
const Schema = mongoose.Schema;
const UserSchema = new Schema({ username: String, password: String });
const User = mongoose.model('User', UserSchema);
javascriptCopy code
passport.use(new LocalStrategy(
function(username, password, done) {
User.findOne({ username: username, password: password }, function(err, user) {
if (err) { return done(err); }
if (!user) { return done(null, false); }
return done(null, user);
});
}
));
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
done(err, user);
});
});
javascriptCopy code
app.use(session({ secret: 'secret', resave: false, saveUninitialized: false }));
app.use(passport.initialize());
app.use(passport.session());
app.use(bodyParser.urlencoded({ extended: true }));
javascriptCopy code
app.get('/', (req, res) => {
res.send('Welcome to the simple app');
});
app.post('/login', passport.authenticate('local', {
successRedirect: '/data',
failureRedirect: '/'
}));
app.get('/data', isAuthenticated, (req, res) => {
res.send('Protected data: Data 1, Data 2');
});
function isAuthenticated(req, res, next) {
if (req.isAuthenticated() && req.body.password === 'joe') {
return next();
}
res.redirect('/');
}
javascriptCopy code
app.listen(3001, () => {
console.log('Server started on http://localhost:3001');
});