Presento inconvenientes al logearme con passport
Este es mi index.js completo
const express = require('express');
const morgan = require('morgan');
const path = require('path');
const exphbs = require('express-handlebars');
const session = require('express-session');
const validator = require('express-validator');
const passport = require('passport');
var cookieParser = require('cookie-parser');
const flash = require('connect-flash');
const MySQLStore = require('express-mysql-session')(session);
const bodyParser = require('body-parser');
const { database } = require('./keys');
// initializations
const app = express();
require('./lib/passport');
// settings
app.set('port', process.env.PORT || 4000);
app.set('views',path.join(__dirname,'views'));
app.engine('.hbs', exphbs({
defaultLayout: 'main',
layoutsDir: path.join(app.get('views'),'layouts'),
partialsDir: path.join(app.get('views'),'partials'),
extname: '.hbs',
helpers: require('./lib/handlebars.js')
}));
app.set('view engine','.hbs');
// middlewares
app.use(morgan('dev'));
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
app.use(session({
secret: 'faztmysqlnodemysql',
resave: false,
saveUninitialized: false,
store: new MySQLStore(database)
}));
app.use(flash());
app.use(passport.initialize());
app.use(passport.session());
app.use(validator());
// global variables
app.use((req, res, next) => {
app.locals.message = req.flash('message');
app.locals.success = req.flash('success');
app.locals.user = req.user;
next();
});
// routers
app.use(require('./routes/index.js'));
app.use(require('./routes/authentication.js'));
//Administrador
app.use('/admin',require('./routes/administrador/index.js'));
app.use('/admin',require('./routes/administrador/usuarios.js'));
app.use('/admin',require('./routes/administrador/contactos.js'));
app.use('/admin',require('./routes/administrador/torre.js'));
app.use('/admin',require('./routes/administrador/parqueadero.js'))
app.use('/admin',require('./routes/administrador/visitante.js'))
app.use('/admin',require('./routes/administrador/informes.js'))
//Operario
app.use('/panel',require('./routes/operario/index.js'));
//app.use('/links',require('./routes/links.js'))
// public
app.use(express.static(path.join(__dirname,'public')));
// starting the server
app.listen(app.get('port'),() => {
console.log('server on port', app.get('port'));
});
En este fracción de código instancia mis variables globales en el index.js que es donde creo que presenta problemas
// global variables
app.use((req, res, next) => {
app.locals.message = req.flash('message');
app.locals.success = req.flash('success');
app.locals.user = req.user;
next();
});
Ahora este es mi archivo de rutas llamado authetication.js
const express = require('express');
const router = express.Router();
const passport = require('passport');
const { isLoggedIn, isNotLoggedIn } = require('../lib/auth');
router.get('/signup', (req, res) =>{
res.render('auth/signup');
});
router.post('/signup', passport.authenticate('local.signup', {
successRedirect: '/profile',
failureRedirect: '/signup',
failureFlash: true
}));
router.get('/signin', (req, res) => {
res.render('auth/signin');
});
router.post('/signin', (req, res, next) =>{
passport.authenticate('local.signin', {
successRedirect: '/profile',
failureRedirect: '/signin',
failureFlash: true
})(req, res, next);
});
router.get('/profile', isLoggedIn, (req, res) => {
if(req.user.tipo === 1){
res.redirect('/admin');
}else if(req.user.tipo === 2){
res.redirect('/panel');
}
});
router.get('/logout', (req, res) => {
req.logOut();
res.redirect('signin');
});
module.exports = router;
Y este es mi archivo controlador de passport
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const pool = require('../database');
const helpers = require('./helpers');
passport.use('local.signin', new LocalStrategy({
usernameField: 'username',
passwordField: 'password',
passReqToCallback: true
}, async (req, username, password, done) => {
const rows = await pool.query('SELECT * FROM users WHERE username = ?', [username]);
if (rows.length > 0) {
const user = rows[0];
const validPassword = await helpers.matchPassword(password, user.password);
if (validPassword) {
console.log(user);
done(null, user, req.flash('success', 'Welcome ' + user.username));
} else {
done(null, false, req.flash('message', 'Incorrect Password'));
}
} else {
return done(null, false, req.flash('message', 'The Username does not exists.'));
}
}));
passport.use('local.signup', new LocalStrategy({
usernameField: 'username',
passwordField: 'password',
passReqToCallback: true
}, async (req, username, password, done) => {
const { nombre, apellido, cedula, telefono } = req.body;
const tipo = 2;
let newUser = {
nombre,
apellido,
cedula,
telefono,
username,
password,
tipo
};
newUser.password = await helpers.encryptPassword(password);
// Saving in the Database
const result = await pool.query('INSERT INTO users SET ? ', newUser);
newUser.id = result.insertId;
return done(null, newUser);
}));
passport.serializeUser((user, done) => {
done(null, user.id);
});
passport.deserializeUser(async (id, done) => {
const rows = await pool.query('SELECT * FROM users WHERE id = ?', [id]);
done(null, rows[0]);
});
Dentro de 'local.signin'
Valido el usuario, esta validacion es correcta al imprimir validPassword
.
El problema es que a pesar de que la validación es exitosa me devuelve a la vista de login, pero si tipeo la url que debería redirigir después del logeo exitoso entra si ningún problema (la vista que dirige después del logeo valida si el usuario esta logeado con isLoggedIn
)
router.get('/profile', isLoggedIn, (req, res) => {
if(req.user.tipo === 1){
res.redirect('/admin');
}else if(req.user.tipo === 2){
res.redirect('/panel');
}
});
Este es el copido de isLoggedIn
module.exports = {
isLoggedIn (req, res, next) {
if (req.isAuthenticated()) {
return next();
}
return res.redirect('/signin');
},
isNotLoggedIn (req, res, next){
if (!req.isAuthenticated()) {
return next();
}
return res.redirect('/profile');
}
};