Saturday 20 May 2017

app.use middleware doesn't execute for routes

I am following this tutorial and I want to do something similiar, when my user access other routes diferents then register and login I want him to send the token to give the access to those routes.

If I do a request to /login or /register everyhting fine.

But when I do a request to /fotos, my app.use(jwtPermission); should be executed.

Here is my app server initial page:

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


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

my jwtPermission file is inside the controller, this controller folder is at the same level then my server initial start file.

Here is what I have in my 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.'
        });
    }
}

if I point to /fotos it never reaches the jwtPermission file, if I change the app.use(jwtPermission) above my register app.use, it works, but the middleware get called for all routes including the /register /login.

Need some help please :).

Thanks!



via Cris dois

No comments:

Post a Comment