Error escaping a url in js express from a middleware

0

I have a problem escaping a Url validation of Token . I am using lib jwt (jsonwebtoken) to restrict the access to request of my api, however I want to leave url /imagem/:parametro without validation by token. Because today when I make the following request /imagem/teste.png it does not let pass without the token.

I'm doing it this way:

My server.js

const express = require('express');
const app = express();
const consign = require('consign');
const bodyParser = require('body-parser');
const fileupload = require('express-fileupload');
const jwt = require('jsonwebtoken');

module.exports = function(){

    //define a url para arquivos estáticos
    app.use('/public', express.static('./app/public'));
    //habilta request e response json
    app.use(bodyParser.urlencoded({ extended: false }));
    app.use(bodyParser.json());
    //habilita o middleware de upload
    app.use(fileupload());

    //verifica se o token é valido
    app.use(function(request, response, next){

        if(request.originalUrl == '/token' || request.originalUrl == '/login' || request.originalUrl == '/imagem/' ){
            return next();
        }else{


            if (request.headers.authorization && request.headers.authorization.split(' ')[0] === 'Bearer') {

                var token = request.headers.authorization.split(' ')[1];

                jwt.verify(token, process.env.SECRET_KEY, function(err, decoded) {
                    if (err) return response.status(500).send({ auth: false, message: 'Falha ao autenticar o token.' });

                    request.userId = decoded.id;
                    next();
                });


            } else if (request.query && request.query.token) {
                next();
                return request.query.token;
            }else{
                response.json("Não Autorizado!");
                next();
            }

        }

    });




    app.use(function(req, res, next) {
      res.header("Access-Control-Allow-Origin", "*");
      res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
      next();
    });



    //carrega modulos na variavel "app"
    consign({ cwd: 'app' }).include('routes').then('controllers').then('helpers').into(app);
    return app;
}

My Image Route

module.exports = function(app) {

    app.get('/imagem/:nome', function(request, response, next){
        var path = require("path");
        var nome_imagem = request.params.nome;
        response.sendFile(path.resolve('app', 'public', '${nome_imagem}') );
    });


    app.post('/imagem', function(request, response, next){

        var file = request.files.img;
        var extensao = file.name.slice('.');
        var nome_arquivo = 'img-' + Date.now() + '.' + extensao;

        file.mv('app/public/${nome_arquivo}', function(err){
            if(err){
                return response.status(500).send(err);
            }
        })

    });


}

Note: I'm using express: 4.16.4      and lib jsonwebtoken: 8.3.0

    
asked by anonymous 01.11.2018 / 20:59

1 answer

1

You can use regular expression within your middleware to check that URL is one of the paths you want to avoid validation.

const { originalUrl: url } = request;

if (/\/(imagem|token|login)(\/|$)/.test(url)) {
  return next();
}

The expression shown above covers the following cases:

  • www.xyz.com/picture
  • www.xyz.com/picture /
  • www.xyz.com/imagem/1
  • www.xyz.com/login
  • www.xyz.com/login/
  • www.xyz.com/login/1
  • www.xyz.com/token
  • www.xyz.com/token /
  • www.xyz.com/token/1
05.11.2018 / 13:31