Passport.js serializeUser and desializeUser are not being called ever? - javascript

Having an issue with Passport-local. It appears neither serializeuser nor deserializeUser get called. After reading other posts on SO, it seems a lot of people who had this issue were not including bodyParser.
Here is my app.js:
var express = require('express');
var app = express();
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var db_config = require('./config/database');
var mongoose = require ('mongoose');
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
//loads passport implementation
require('./config/passport')(app);
//loads all routes
require('./config/routes')(app);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
//initialize connection to database
mongoose.connect(db_config.development);
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// development error handler
// will print stacktrace
if (app.get('env') === 'test') {
//initialize connection to database
mongoose.connect(db_config.test);
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
if(app.get('env') === 'production'){
//initialize connection to database
mongoose.connect(db_config.production);
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
}
module.exports = app;
Here is config/passport.js:
module.exports = function(app){
var passport = require ('passport');
var LocalStrategy = require('passport-local').Strategy;
var session = require('express-session');
var User = require('../models/user.js');
// =========================================================================
// passport session setup ==================================================
// =========================================================================
// required for persistent login sessions
// passport needs ability to serialize and unserialize users out of session
// used to serialize the user for the session
passport.serializeUser(function(user, done) {
console.log('serialize');
done(null, user._id);
});
// used to deserialize the user
passport.deserializeUser(function(id, done) {
console.log('deserialize');
User.findById(id, function(err, user) {
done(err, user);
});
});
//configure passport http-basic strategy
passport.use(new LocalStrategy({
usernameField: "username",
passwordField: "password"
},
function(username, password, done){
User.findOne({username: username}, function(err, user){
if(err) return done(err);
if(!user || !user.validatePassword(password)) return done(null, false);
console.log("inside LocalStrategy: " + user);
return done(null, user);
});
}));
//setup express-session
app.use(session({
secret: "secret",
saveUninitialized: true,
resave: true
}));
app.use(passport.initialize());
app.use(passport.session());
return passport;
};
Here is my routes.js:
module.exports = function(app){
var routes = require('../routes/index');
var users = require('../routes/users');
var walks = require('../routes/walks');
var isAuthenticated = function(req, res, next){
if(req.isAuthenticated())
next();
res.status(401).send('You must login first.');
};
app.use('/', routes);
app.all('*', isAuthenticated);
app.use('/users', users);
app.use('/walks', walks);
};
Here is the routes/index.js:
var router = require('express').Router();
var passport = require('passport');
var controller = require('../controllers/index');
router.get('/', controller.index);
router.post('/signup', controller.signup);
router.post('/login', passport.authorize('local'), controller.login);
module.exports = router;
And finally here is the controller/index.js:
var User = require('../models/user.js');
var handleError = require('../handlers/error');
var controller = {};
controller.index = function(req, res, next) {
res.render('index', { title: 'Express' });
};
controller.signup = function(req, res){
console.log(req.body);
var user = new User();
user.username = req.body.username;
user.password = req.body.password;
user.save(function(err, user){
if(err) {
console.log(err.code);
handleError(res, err);
}
return res.send(user);
});
};
controller.login = function(req, res){
console.log('inside /login');
console.log('req.user: ' + req.user);
console.log('req.session: ');
console.log(req.session);
console.log('req.body: ');
console.log(req.body);
res.send(req.user);
};
module.exports = controller;
In POSTMAN I am first creating a user with a POST request to /signup with:
{
"username": "bob",
"password": "password123"
}
Then I POST to /login with the same credentials, here is the output:
inside LocalStrategy: { __v: 0,
username: 'bob',
password: '$2a$10$Oa/Q9C5Elsoa0P4427P6fOXWIKerlD937FYgLFrwCWwXxGW1gbsoW',
_id: 5685d6845c7b208693b71091 }
inside /login
req.user: undefined
req.session:
Session {
cookie:
{ path: '/',
_expires: null,
originalMaxAge: null,
httpOnly: true } }
req.body:
{ username: 'bob', password: 'password123' }
POST /login 200 205.704 ms - -
As you can see, the console.log() in both serializeUser and deserializeUser do not get called. Why is this? I'm at a complete loss here, I honestly have no idea what else to try.

This:
router.post('/login', passport.authorize('local'), controller.login);
Should be this:
router.post('/login', passport.authenticate('local'), controller.login);
passport.authorize() is meant for connecting third-party authorization responses to already-authenticated users.

Related

How to access app.locals variable in handlebars

app.js
var debug = require('debug');
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
javvar mongoose = require('mongoose');
var session = require('express-session');
var db = require('./dbconn');
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
console.log('we are connected!');
});
var index = require('./routes/index');
var users =
require('./routes/users');
var signup = require('./routes/signup');
var login = require('./routes/login');
var adreqform =
require('./routes/adreqform') var dashboard =
require('./routes/dashboard')
var app = express();
// view engine setup app.set('views', path.join(__dirname, 'views'));
app.engine('hbs', exphbs({
extname: '.hbs',
defaultLayout: 'layout'
}));
app.set('view engine', 'hbs');
// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname,
'public')));
app.use(session({
secret: 'gh jewellery',
resave: true,
saveUninitialized: false
}));
app.use(function(req, res, next) {
app.locals.currentUser = req.session.user;
next();
});
app.use('/', index);
app.use('/users', users);
app.use('/dashboard',
dashboard);
app.use('/signup', signup);
app.use('/login', login);
app.use('/adreqform', adreqform);
// catch 404 and forward to error handler app.use(function (req, res,
next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler // will print stacktrace if
(app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler // no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
app.set('port', process.env.PORT || 3000);
module.exports = app;
var server = app.listen(app.get('port'), function() {
debug('Express server listening on port ' + server.address().port);
});
Notice I assign app.locals.currentUser = req.session.user; above and req.session.user gets set when my route /login is hit and here is it's code.
login.js
var express = require('express');
var router = express.Router();
var User = require('../models/user.model.js');
var app = require('../app');
/* GET signup page. */
router.get('/', function(req, res, next) {
res.render('login');
});
router.post('/', function(req, res, next) {
User.findOne({
email: req.body.email
}, function(err, user) {
var logged = false;
if (err) {
console.log(err);
} else if (!user) {
res.render('login', {
errnoacc: 'User does not exist! Please register.'
})
} else if (user && req.body.password == user.password) {
req.session.user = user;
res.render('dashboard');
} else {
res.render('login', {
errpass: 'Password does not match. Please try again!'
});
}
});
next();
});
module.exports = router;
In the above code when POST is hit, I assign req.session.user = user; if all is good I render the dashboard view, there are a layout.hbs which has navbar where I want to use app.locals.currentUser to show currentUser object.
Using in my layouts.hbs {{currentUser.username}} doesn't work.
I am new to expressjs development so I know I am missing something.
app.locals holds settings for all application, if you app gets more than one user it will overwrite the information.
app.use(function(req, res, next) {
app.locals.currentUser = req.session.user;
next();
});
You may use res.locals:
app.use(function(req, res, next){
res.locals.user = req.user;
res.locals.authenticated = ! req.user.anonymous;
next();
});
Then you can access in handlebar like:
p #{user.userName}

Nodejs Passport req.user undefined

When im logging in the req.user but i gone undefined and req.isAuthenticated() is False. Maybe I'm doing something wrong, I ran out of ideas.
Also deserializeUser is never called, instead serializeUser still working well.
I also check all other issue, almost of them just rearranged the position of bodyParser and cookieParser but it's not work with my issue.
app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var cors = require('cors')
var mongoose = require('mongoose');
mongoose.Promise = global.Promise;
var session = require('express-session');
var passport = require('passport');
var passportconfig = require('./config/passport')(passport);
var flash = require('connect-flash');
// var index = require('./routes/index');
var wallet = require('./routes/api/walletAPI');
var index = require('./routes/index');
var app = express();
//mongoose connection
mongoose.connect('mongodb://localhost:27017/wallet');
var dbMongo = mongoose.connection;
dbMongo.on('err', console.error.bind(console, 'connect fail'));
dbMongo.once('open', function () {
console.log('mongo connected');
});
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Credentials', true);
res.header('Access-Control-Allow-Origin', req.headers.origin);
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept');
if ('OPTIONS' == req.method) {
res.send(200);
} else {
next();
}
});
//Enable All CORS Requests
// app.use(cors({credentials: true}));
app.use(logger('dev'));
app.use(cookieParser());
const cookieExpirationDate = new Date();
const cookieExpirationDays = 365;
cookieExpirationDate.setDate(cookieExpirationDate.getDate() + cookieExpirationDays);
app.use(session({secret: 'keyboard cat', saveUninitialized: true, resave: true, cookie: {
secure: false,
httpOnly: true,
expires: cookieExpirationDate // use expires instead of maxAge
}}));
app.use(passport.initialize());
app.use(passport.session());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, 'public')));
app.use(function(err, req, res, next) {
console.log(err);
});
app.use(flash());
// app.use('/', index);
app.use('/wallet/api', wallet);
app.use('/', index);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// Session-persisted message middleware
app.use(function(req, res, next){
var err = req.session.error,
msg = req.session.notice,
success = req.session.success;
delete req.session.error;
delete req.session.success;
delete req.session.notice;
if (err) res.locals.error = err;
if (msg) res.locals.notice = msg;
if (success) res.locals.success = success;
next();
});
// error handler
app.use(function (err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
walletAPI.js
var express = require('express');
var router = express.Router();
var walletController = require('../../controller/walletController');
router.post('/login', function (req, res, next) {
var result = walletController.log_in(req, res, next);
req.session.save();
})
walletController.js
var history = require('../models/history');
var wallet = require('../models/wallet');
var md5 = require('md5');
var passport = require('passport');
exports.log_in = passport.authenticate('local-signin', {
successRedirect: '/a',
failureRedirect: '/login',
failureFlash: 'Invalid username or password.',
successFlash: 'Success.'
});
passport.js
var LocalStrategy = require('passport-local').Strategy;
var User = require('../models/wallet');
var md5 = require('md5');
module.exports = function(passport){
//Passport configuration
passport.serializeUser(function(user, done) {
console.log('user:')
console.log(user._id)
done(null, user._id);
});
passport.deserializeUser(function(id, done) {
console.log('id:')
console.log(id)
User.findById(id, function(err, user) {
done(err, user);
});
done(null, id);
});
passport.use('local-signin',new LocalStrategy({
usernameField : 'username',
passwordField : 'password',
passReqToCallback: true,
},
function(req, username, password, done) {
process.nextTick(function () {
User.findOne({'username': username}, function (err, user) {
// console.log(user)
if (err) {
return done(err);
}
if (!user) {
return done(null, false, req.flash('loginMessage', 'No user found.'));
}
else if (user.password !== md5(password)) {
return done(null, false, req.flash('loginMessage', 'Oops! Wrong password.'));
}
return done(null, user);
});
})
}
));
}

Node.js - user Authentication with Passport (Learn Node.js by building 10 projects course)

I'm following a tutorial which probably is outdated in some moments, but anyway I would like to finish it.
Here is the problem - I stacked on user Authentication with Passport and can't Login into my website though there are no mistakes in my code and even in console (what is the most terrible part cuz I can't see what actually is wrong). After clicking button "submit" it must redirect me to members area page but it simply doesn't respond. And no errors on console, like everything is working fine! I'm sorry if I did or said something wrong, it's my first question here :) And thank you for any help or advice! Here are my code snippets:
// In app.js:
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var expressValidator = require('express-validator');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var bodyParser = require('body-parser');
var multer = require('multer');
var uploads = multer({dest: './uploads'});
var flash = require('connect-flash');
var mongo = require('mongodb');
var mongoose = require('mongoose');
var db = mongoose.connection;
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// Handle file uploads
var upload = multer({ dest: './uploads' });
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
// Handle Express Sessions
app.use(session({
secret:'secret',
saveUninitialized: true,
resave: true
}));
// passport
app.use(passport.initialize());
app.use(passport.session());
// Validator
app.use(expressValidator({
errorFormatter: function(param, msg, value) {
var namespace = param.split('.')
, root = namespace.shift()
, formParam = root;
while(namespace.length) {
formParam += '[' + namespace.shift() + ']';
}
return {
param : formParam,
msg : msg,
value : value
};
}
}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(flash());
app.use(function (req, res, next) {
res.locals.messages = require('express-messages')(req, res);
next();
});
app.get('*', function(req, res, next){
res.locals.user = req.user || null;
next();
});
app.use('/', routes);
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
<!-- begin snippet: js hide: false console: true babel: false -->
// In users.js in routes:
var express = require('express');
var router = express.Router();
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var User = require('../models/user');
var multer = require('multer');
var uploads = multer({dest: './uploads'});
/* GET users listing. */
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
router.get('/register', function(req, res, next) {
res.render('register', {
'title': 'Register'
});
});
router.get('/login', function(req, res, next) {
res.render('login', {
'title': 'Login'
});
});
router.post('/register', uploads.single('profileimage'), function(req, res, next) {
var name = req.body.name;
var email = req.body.email;
var username = req.body.username;
var password = req.body.password;
var password2 = req.body.password2;
// Check for Image Field
if (req.file) {
console.log('uploading File...');
// File Info
var profileImageOriginalName = req.files.profileimage.originalname;
var profileImageName = req.files.profileimage.name;
var profileImageMime = req.files.profileimage.mimetype;
var profileImagePath = req.files.profileimage.path;
var profileImageExt = req.files.profileimage.extension;
var profileImageSize = req.files.profileimage.size;
} else {
// Set a Default Image
var profileImageName = 'noimage.png';
}
// Form Validation
req.checkBody('name','Name field is required').notEmpty();
req.checkBody('email','Email field is required').notEmpty();
req.checkBody('email','Email not valid').isEmail();
req.checkBody('username','Username field is required').notEmpty();
req.checkBody('password','Password field is required').notEmpty();
req.checkBody('password2','Password do not match').equals(req.body.password);
// Check for errors
var errors = req.validationErrors();
if(errors){
res.render('register', {
errors: errors,
name: name,
email: email,
username: username,
password: password,
password2: password2
});
} else {
var newUser = new User({
name: name,
email: email,
username: username,
password: password,
profileImage: profileImageName
});
// Create User
User.createUser(newUser, function(err, user){
if(err)throw err;
console.log(user);
});
//Success Message
req.flash('success', 'You are now registered and may log in');
res.location('/');
res.redirect('/');
}
});
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
User.getUserById(id, function(err, user) {
done(err, user);
});
});
passport.use(new LocalStrategy(
function(username, password, done){
User.getUserByUsername(username, function(err, user){
if(err) throw err;
if(!user){
console.log('Unknown User');
return done(null, false, {message: 'Unknown User'});
}
User.comparePassword(password, user.password, function(err, isMatch){
if(err) throw err;
if(isMatch){
return done(null, user);
} else {
console.log('Invalid Password');
return done(null, false, {message: 'Invalid Password'});
}
});
});
}
));
router.post('/login', passport.authenticate('local',{failureRedirect: '/users/login', failureFlash: 'Invalid username or password'}), function(req, res){
console.log('Authentication Successful');
req.flash('success', 'You are logged in');
res.redirect('/');
});
router.get('/logout', function(req, res){
req.logout();
req.flash('success', 'You have logged out');
res.redirect('/users/login');
});
module.exports = router;
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
<!-- end snippet -->
// In package.json:
{
"name": "nodeauth",
"version": "1.0.0",
"private": true,
"scripts": {
"start": "node ./bin/www"
},
"dependencies": {
"body-parser": "~1.15.1",
"cookie-parser": "~1.4.3",
"debug": "~2.2.0",
"express": "~4.13.4",
"jade": "~1.11.0",
"morgan": "~1.7.0",
"serve-favicon": "~2.3.0",
"mongodb":"*",
"mongoose":"*",
"connect-flash":"*",
"express-validator":"*",
"express-session":"*",
"express-messages":"*",
"passport":"*",
"passport-local":"*",
"passport-http":"*",
"multer":"*"
}
}
// In user.js in models:
var mongoose = require('mongoose');
var bcrypt = require('bcrypt');
mongoose.connect('mongodb://localhost/nodeauth');
var db = mongoose.connection;
// User Schema
var UserSchema = mongoose.Schema({
username: {
type: String,
index: true
},
password: {
type: String,
required: true,
bcrypt: true
},
email: {
type: String
},
name: {
type: String
},
profileimage: {
type: String
}
});
var User = module.exports = mongoose.model('User', UserSchema);
module.exports.comparePassword = function(candidatePassowrd, hash, callback){
bcrypt.compare(candidatePassowrd, hash, function(err, isMatch){
if(err) return callback(err);
callback(null, isMatch);
});
}
module.exports.getUserById = function(id, callback){
User.findById(id, callback);
}
module.exports.getUserByUsername = function(username, callback){
var query = {username: username};
User.findOne(query, callback);
}
module.exports.createUser = function(newUser,callback){
bcrypt.hash(newUser.password, 10, function(err, hash){
if(err) throw err;
// Set Hashed password
newUser.password = hash;
// Create User
newUser.save(callback);
});
};
I encountered the same issue. The problem is the form. Remove the enctype part and it works!
Edit: The reason why removing the enctype caused it to work is because then it does not need Multer. Multer's API changed since this was recorded. You need to include uploads.single('profileimage') as the second param in the post.
Please remember to define the require for multer in the new way as well.
Example:
var multer = require('multer');
// To handle the inclusion of the extension in the filename
var path = require('path')
var storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, './public/images/uploads')
},
filename: function (req, file, callback) {
callback(null, Date.now() + path.extname(file.originalname)) //Appending extension
}
})
var upload = multer({ storage: storage });
The above example was taken from the next project in the course that required an upload of an image. It was only when hitting this project that I was able to find the required workaround to make it work as its supposed it. Reading the documentation on multer helped as well.

Passport-init.js authentication is not working in nodejs

I am new to nodejs and trying to develop nodejs demo application referring this article. I followed all steps
and its first phase is working fine for me. But after adding passport authentication it is not working
here is my app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var passport = require('passport');
//add for Mongo support
//var mongoose = require('mongoose');
var api = require('./routes/api');
var authenticate = require('./routes/authenticate')(passport);
//connect to Mongo
// mongoose.connect('mongodb://localhost:27017/MEAN_Stack');
// require('./models/models.js');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(session({
secret: 'keyboard cat'
}));
//app.use(bodyParser.json());
//app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(passport.initialize());
app.use(passport.session());
//// Initialize Passport
var initPassport = require('./passport-init');
initPassport(passport);
app.use('/api', api);
app.use('/auth', authenticate);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
here is my api.js
var express = require('express');
var router = express.Router();
//Register the authentication middleware
//router.use('/posts');
//api for all posts
router.route('/posts')
//create a new post
.post(function(req, res){
//TODO create a new post in the database
res.send({message:"TODO create a new post in the database rhushikesh"});
})
.get(function(req, res){
//TODO get all the posts in the database
res.send({message:"TODO get all the posts in the database"});
})
//api for a specfic post
router.route('/posts/:id')
//create
.put(function(req,res){
return res.send({message:'TODO modify an existing post by using param ' + req.param.id});
})
.get(function(req,res){
return res.send({message:'TODO get an existing post by using param ' + req.param.id});
})
.delete(function(req,res){
return res.send({message:'TODO delete an existing post by using param ' + req.param.id})
});
module.exports = router;
here is my authenticate.js
var express = require('express');
var router = express.Router();
module.exports = function(passport){
//sends successful login state back to angular
router.get('/success', function(req, res){
res.send({state: 'success', user: req.user ? req.user : null});
});
//sends failure login state back to angular
router.get('/failure', function(req, res){
res.send({state: 'failure', user: null, message: "Invalid username or password1111"});
});
//log in
router.post('/login', passport.authenticate('login', {
successRedirect: '/auth/success',
failureRedirect: '/auth/failure'
}));
//sign up
router.post('/signup', passport.authenticate('signup', {
successRedirect: '/auth/success',
failureRedirect: '/auth/failure'
}));
//log out
router.get('/signout', function(req, res) {
req.logout();
res.redirect('/');
});
return router;
}
here is my passport-init.js
var LocalStrategy = require('passport-local').Strategy;
var bCrypt = require('bcrypt-nodejs');
//temporary data store
var users = {};
module.exports = function(passport){
// Passport needs to be able to serialize and deserialize users to support persistent login sessions
passport.serializeUser(function(user, done) {
console.log('serializing user:',user.username);
return done(null, user.username);
});
passport.deserializeUser(function(username, done) {
return done('we have not implemented this', false);
});
passport.use('login', new LocalStrategy({
passReqToCallback : true
},
function(req, username, password, done) {
if(!users[username]){
console.log('User Not Found with username '+username);
return done(null, false);
}
if(isValidPassword(users[username], password)){
//sucessfully authenticated
return done(null, users[username]);
}
else{
console.log('Invalid password '+username);
return done(null, false)
}
}
));
passport.use('signup', new LocalStrategy({
passReqToCallback : true // allows us to pass back the entire request to the callback
},
function(req, username, password, done) {
// if (users[username]){
// console.log('User already exists with username: ' + username);
// return done(null, false);
// }
//store user in memory
users[username] = {
username: username,
password: createHash(password)
}
console.log(users[username].username + ' Registration successful');
return done(null, users[username]);
})
);
var isValidPassword = function(user, password){
return bCrypt.compareSync(password, user.password);
};
// Generates hash using bCrypt
var createHash = function(password){
return bCrypt.hashSync(password, bCrypt.genSaltSync(10), null);
};
};
When i try to hit the signup api from postman it always redirect to failure api. I also have tried with the debugger but i am not getting the controller over there.
just uncomment following line in app.js
//app.use(bodyParser.json());
//app.use(bodyParser.urlencoded({ extended: false }));
and update passport-init.js
passport.deserializeUser(function(username, done) {
return done('we have not implemented this', false);
});
to
passport.deserializeUser(function(username, done) {
return done(null, users[username]);
});

Include the username in the redirect URL path after authenticating the user in Node.js using PassportJS

I'm using PassportJS to create a login/sign-up program. Then to enter I try to include the username of the user in the path of the redirect. To be more precise, when the user does a login with username and password I want to redirect him/her to the page localhost:3000/library?'username'. How can I do it?
var config = require('./config');
var express = require('express');
var path = require('path');
var logger = require('morgan');
var bodyParser = require('body-parser');
var dustjs = require('adaro');
var app = express();
var multer = require('multer');
var passport = require('passport');
LocalStrategy = require('passport-local').Strategy;
var mongoose = require('mongoose');
require('./models');
require('express-session');
// Connect to MongoDB here
var mongoose = require('mongoose');
mongoose.connect(config.mongoUrl + config.mongoDbName);
//passport
// --------------- USER PART --------------------\\
var User = mongoose.model('User');
passport.use(new LocalStrategy({
usernameField:'userName',
passwordField:'password'
},
function(username, password, done) {
User.findOne({userName: username}, function (err, user) {
if (err) { return done(err); }
// Return an error as in Node
if (!user) {
return done(null, false, { message: 'Incorrect username.' });
// If user does not exist return the error and the message
}
user.isValidPassword(password, function(err,isMatch){
if (isMatch==true){
return done(null, true);
// Authentication is good, the password is valid
}else{
return done(null, false, {message:"Incorrect password! "})
}
});
});
}
));
passport.serializeUser(function(users, done) {
done(null, 0);
// Invoke passport with user._id authenticated
});
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
// Deserializza e cerca attraverso l'id
done(err, user);
});
});
// --------------- EDN USER PART --------------------\\
/*--- Configure the multer. used to upload the track from our pc on the server ---*/
app.use(multer({ dest: './public/tracks_folder/',
rename: function (fieldname, filename) {
return filename;
}
}));
// Register model definition here
require('./models');
// dustjs view engine setup
app.engine('dust', dustjs.dust());
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'dust');
// USER
app.use(passport.initialize());
app.use(passport.session());
//configure app
app.use(logger('dev'));
app.use(bodyParser.urlencoded({ extended: false })); // parse application/x-www-form-urlencoded
app.use(bodyParser.json()); // parse application/json
app.use(express.static(path.join(__dirname, 'public')));
// Initialize routers here
var routers = require('./routes/routers');
app.use('/', routers.root);
app.use('/albums', routers.albums);
app.use('/artists', routers.artists);
app.use('/tracks', routers.tracks);
app.use('/users', routers.users);
// USER
app.use('/signup', routers.signup);
app.use('/library', routers.library);
EDIT OF GET
app.get('/login', function(req, res, next) {
passport.authenticate('local', function(err, user, info) {
if (err) { return next(err); }
if (!user) { return res.redirect('/login'); }
req.logIn(user, function(err) {
if (err) { return next(err); }
return res.redirect('/library/' + user.username);
});
})(req, res, next);
});
app.post('/login',
passport.authenticate('local', { successRedirect: '/library',
failureRedirect: '/'}));
// END USER
module.exports = app;

Categories