Friday 19 May 2017

router.use middleware don't get called

I have a simple server application running with NodeJS, and i tried to implement the route protecting that is in this tutorial, i already have the token that works every time i login

So this midleware should be called to all routes except register and login, soo i did this in my initial setup:

    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 debug = require('debug')('express-sequelize');
var http = require('http');
var models = require('./models');
var jwt = require('jsonwebtoken');
var jwtPermission = require('./controller/jwtPermission');
var fotos = require('./routes/fotos');
var app = express();
var router = express.Router();


// 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')));

router.use('/',require('./routes/index'));
router.use(jwtPermission);
router.use('/fotos',fotos);

the middleware that doesn't get called is jwtPermission, so i have a routes folder where i have a index, and the authentication file(that has login and register), for the jwtPermission i just have the controller set as you guys can see i require a controller.

I have a console.log inside that controller but it never get called.

jwtPermission

var jwt = require('jsonwebtoken');

var jwtConfig = require('../config/jwt');

module.exports = function(req, res, next) { console.log("entered");

// check header or url parameters or post parameters for token
var token = req.body.token || req.query.token || req.headers['x-access-token'];
      console.log(req.headers['x-access-token']);
// decode token
if (token) {
    // verifies secret and checks exp
    jwt.verify(token,jwtConfig.secret, function (err, decoded) {
        if (err) {
            return res.json({ success: false, message: 'Failed to authenticate token.' });
        } else {
            // if everything is good, save to request for use in other routes
            req.decoded = decoded;
            next();
        }
    });
} else {
    // if there is no token
    // return an error
    return res.status(403).send({
        success: false,
        message: 'No token provided.'
    });
}

}



via Cris dois

No comments:

Post a Comment