mkdir passport-local
npm init
# Use default values for npm init prompts
npm install --save express
npm install --save connect-flash
npm install --save express-session
npm install --save body-parser
npm install --save cookie-parser
npm install --save passport
npm install --save passport-local
In the root folder create a file called "auth.js" with the following content.
var passport = require('passport'),
LocalStrategy = require('passport-local').Strategy,
user = { // This a hard-coded user
_id: 1,
username: 'john',
email: '[email protected]',
password: 'password'
};
// Register a login strategy
passport.use('login', new LocalStrategy(
function(username, password, done) {
// This should check again db
if(username === user.username && password === user.password) {
return done(null, user);
}
else {
done(null, false, { message: 'Invalid username and password.' });
}
}
));
// Required for storing user info into session
passport.serializeUser(function(user, done) {
done(null, user._id);
});
// Required for retrieving user from session
passport.deserializeUser(function(id, done) {
// The user should be queried against db
// using the id
done(null, user);
});
module.exports = passport;
In the root folder create a file called "app.js" with the following content.
var express = require('express'),
app = express(),
session = require('express-session'),
flash = require('connect-flash'),
session = require('express-session'),
auth = require('./auth.js'),
bodyParser = require('body-parser');
app.use('/', express.static(__dirname + '/public'));
app.use(session({
secret: 'some-secret',
saveUninitialized: false,
resave: true
}));
// For parsing post request's data/body
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
// Tells app to use password session
app.use(auth.initialize());
app.use(auth.session());
app.use(flash());
// Set up routes
app.get('/', function(req, res) {
if(req.user) {
res.send(
'<p>You\'re logged in as <strong>' + req.user.username + '</strong>.</p>'
+ '<p><a href="/logout">Log out</a></p>'
);
}
else {
res.send('<p><a href="/login">Login</a></p>');
}
});
app.get('/login', function(req, res) {
res.send(
'<form action="/login" method="POST">'
+ '<h2>Login</h2>'
+ '<p><input name="username"></p>'
+ '<p><input name="password"></p>'
+ '<p><input type="submit" value="Login"></p>'
+ '<p style="color: red;">' + req.flash('error') + '</p>'
+ '</form>'
);
});
app.get('/logout', function(req, res) {
req.logout();
res.redirect('/');
});
app.post('/login',
auth.authenticate('login', {
successRedirect: '/',
failureRedirect: '/login',
failureFlash: true
})
);
var server = app.listen(3000, function() {
var port = server.address().port;
console.log('Server running on http://127.0.0.1:%s', port);
});
what is the commands to set password and user name i didn't get it????
how i will set for localhost ? "lt --port 3000"