1
I’m using Passport and Passport-local to authenticate with Nodejs, but the req.isAuthenticated method always returns me false, not even serialize when I log in. I tried to put a req.login() but then gives me another error: serializing user:false Error: Failed to serialize user into Session
server.js:
var express = require('express');
var session = require('express-session');
var cookieParser = require('cookie-parser');
var app = express();
var bodyParser = require('body-parser');
var morgan = require('morgan');
var mongoose = require('mongoose');
var config = require('./config/database');
var cors = require('cors');
mongoose.connect(config.database, function(err, db){
if(!err){
console.log('Conectado');
}
});
var passport = require('passport');
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use(cookieParser());
app.use(session({ secret: 'SecretSession'}));
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static(__dirname + '/public'))
app.use(morgan('dev'));
app.use(cors());
var initPassport = require('./config/passport');
initPassport(passport);
var index = require('./config/index')(passport);
app.use('/', index);
server.listen(3030, function(){
console.log('Rodando ');
});
Passport.js:
var User = require('../app/models/user');
var login = require('./login');
var signup = require('./signup');
module.exports = function(passport){
passport.serializeUser(function(user, done) {
console.log('serializing user: ');console.log(user);
done(null, user._id);
});
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
console.log('deserializing user:',user);
done(err, user);
});
});
login(passport);
signup(passport);
}
login js.:
var LocalStrategy = require('passport-local').Strategy;
var User = require('../app/models/user');
var bCrypt = require('bcrypt-nodejs');
module.exports = function(passport){
passport.use('login', new LocalStrategy({
passReqToCallback: true
},
function(req, username, password, done){
User.findOne({'username': username}, function(err, user){
if(err){
return done(err);
}
if(!user){
console.log('NENHUM USUARIO ENCONTRADO COM O LOGIN ' + username);
return done(null, false);
}
if(!validatePassword(user, password)){
console.log('PASSWORD INVALIDO');
return done(null, false);
}
return done(null, user);
});
}
));
var validatePassword = function(user, password){
return bCrypt.compareSync(password, user.password);
}
}
signup.js
var LocalStrategy = require('passport-local').Strategy;
var User = require('../app/models/user');
var bCrypt = require('bcrypt-nodejs');
module.exports = function(passport){
passport.use('signup', new LocalStrategy({
passReqToCallback: true
}, function(req, username, password, done){
findOrCreateUser = function(){
User.findOne({'username' : username}, function(err, user){
if(err){
console.log('ocorreu um erro ' + err);
return done(err)
}
if(user){
console.log('usuario ja cadastrado');
return done(null, false);
}else{
var novoUsuario = new User();
novoUsuario.username = username;
novoUsuario.password = createHash(password);
novoUsuario.nome = req.param('nome');
novoUsuario.email = req.param('email');
novoUsuario.save(function(err){
if(err){
throw err;
}
console.log('usuario cadastrado com sucesso');
return done(null, novoUsuario);
});
}
});
}
process.nextTick(findOrCreateUser);
}));
var createHash = function(password){
return bCrypt.hashSync(password, bCrypt.genSaltSync(10), null);
}
}
index js.:
var express = require('express');
var app = express();
var router = express.Router();
var jwt = require('jwt-simple');
var isAuthenticated = function(req, res, next){
if(req.isAuthenticated()){
return next();
}else{
res.redirect('/');
}
}
module.exports = function(passport){
router.post('/api/login', function(req, res, next){
passport.authenticate('login', function(err, user){
if(err){
res.json({sucesso: false, mensagem: 'Erro ao logar', erro: err});
}
else{
var token = jwt.encode(user, 'JwTaUtHaNGULAR');
return res.send({sucesso: true, token: 'JWT ' + token, mensagem: 'Autenticação OK'});
}
})(req, res, next);
});
router.post('/api/cadastro', function(req, res, next){
passport.authenticate('signup', function(err, user){
if(err){
res.json({sucesso: false, mensagem: 'Erro ao criar usuário', erro: err});
}
else{
res.json({sucesso: true, mensagem: 'Usuario criado com sucesso'});
}
})(req, res, next);
});
router.get('/api/dashboard/users', isAuthenticated ,function(req, res){
console.log('request', req)
Usuario.find({'_id': {$ne: id_user}}, function(err, usuario){
res.json({sucesso: true, user: usuario});
});
});
return router;
}
models/user.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var UsuarioSchema = new Schema({
username: {
type: String,
required: true,
unique: true
},
password: {
type: String,
required: true
},
nome: {
type: String,
require: false
},
email: {
type: String,
unique: false,
require: false
}
});
module.exports = mongoose.model('Usuario', UsuarioSchema);