Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Hello World - Passport with LocalStrategy
const express = require('express');
const passport = require('passport');
const app = express();
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const session = require('express-session');
const LocalStrategy = require('passport-local').Strategy;
passport.serializeUser((user, done) => { console.log('serialize'); done(null, user); } );
passport.deserializeUser((user, done) => { console.log('deserialize'); done(null, user); });
passport.use(new LocalStrategy(
(username, password, done) => {
if (password === 'secret') {
done(null, { username, password });
} else {
done(null, false, { message: 'Incorrect username.' });
}
}
));
function ensureAuthenticated(req, res, next) {
if (req.isAuthenticated()) {
return next();
}
res.redirect('/');
}
app.use(cookieParser());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(session({ secret: 'anything' }));
app.use(passport.initialize());
app.use(passport.session());
app.post('/login',
passport.authenticate('local', { successRedirect: '/protected', failureRedirect: '/' })
);
app.get('/logout', (req, res) => {
req.logout();
res.redirect('/');
});
app.get('/', (req, res) => {
res.send(`
<form action="/login" method="post">
<div>
<label>Username:</label>
<input type="text" name="username"/>
</div>
<div>
<label>Password:</label>
<input type="password" name="password"/>
</div>
<div>
<input type="submit" value="Log In"/>
</div>
</form>
`);
});
app.get('/protected', ensureAuthenticated, (req, res) => { console.log(req.user); res.json(req.user) });
app.listen(3000, () => console.log('Example app listening on port 3000!'));
{
"name": "passport-test",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.18.2",
"cookie-parser": "^1.4.3",
"express": "^4.16.2",
"express-session": "^1.15.6",
"passport": "^0.4.0",
"passport-local": "^1.0.0"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment