Tuesday, 16 May 2017

app.use don't get fired

I am trying to use a middleware on my aplication to check on all routes if the token is passed, at the moment i want to test it just with the /users route, so i did this on my app file:

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('./routes/jwt');
var app = express();


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

app.use('/users',jwt); // executa a verificacao do token em todas as rotas excepto o registo e login


// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

then in my jwt file i did this:

var express = require('express');
var User = require('../models').User;
var router = express.Router();
var jwt = require('jsonwebtoken');

// route middleware to verify a token
module.exports = function () {
    return 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'];
        // decode token
        if (token) {
            // verifies secret and checks exp
            jwt.verify(token, app.get('superSecret'), 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.'
            });

        }
    }
};

my jwt file is inside the routes folder that is at same level as the app file, any sugestion? it doesn't hit the route



via Cris dois

No comments:

Post a Comment