0
I’m having a problem escaping a Url of the validation of Token. I’m using the lib jwt (jsonwebtoken) to restrict accesses to my api request, but I want to leave the url /imagem/:parametro
without token validation. Because today when I do the following request /imagem/teste.png
he won’t let go 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 am using the express: 4.16.4 and the lib jsonwebtoken: 8.3.0
If I’m not mistaken express allows you to pass regular expressions, try to exchange
app.use(function(request, response, next){
forapp.get('/[^imagem]', function(request, response, next){
in the middleware validating the token. From a look in that question related– Costamilam
@Guilhermecostamilam did not work, continues not to pass the route.
– William
Don’t you better isolate the routes and put the
middleware
only the ones you want?– Sorack
@Sorack, yes for a small application is valid, but with the growth of the application would not be viable whenever a route was created put the middleware.
– William
Changes in your
if
for conditions to remain so:request.originalUrl.indexOf('/imagem') !== -1)
– Sorack
@Sorack, vlw worked perfectly.
– William