JWT Token和Multer用于文件上传(节点)

时间:2016-01-26 22:29:18

标签: node.js express jwt multer

我需要一些帮助来确定如何使其正常工作 - 我已经过测试,并在我的用户'上进行了JWT身份验证和SSL工作。路线。我试图安全地允许用户上传音频文件,也使用JWT和SSL路线。

身份验证中间件可以工作,当我注释掉身份验证中间件时,multer可以让我上传文件。但是,当我离开中间件时,上传的文件是在我的系统上创建的,但文件无法正常上传,我收到404错误。

感谢您的帮助!

server.js(主文件)

var express     = require('express')
, app           = express()
, passport      = require('passport')
, uploads       = require('./config/uploads').uploads
, user_routes   = require('./routes/user')
, basic_routes  = require('./routes/basic')
, jwt           = require('jwt-simple');

// get our request parameters
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());


// Use the passport package in our application
app.use(passport.initialize());
require('./config/passport')(passport);

//double check we have an ssl connection
function ensureSec(req, res, next) {
    if (req.headers['x-forwarded-proto'] == 'https') {
        return next();
    } else {
         console.log('NOT SSL PROTECTED! rejected connection.');
         res.redirect('https://' + req.headers.host + req.path);
    }
}

app.use(ensureSec);


//authenticate all user routes with passport middleware, decode JWT to see
//which user it is and pass it to following routes as req.user
app.use('/user', passport.authenticate('jwt', {session:false}), user_routes.middleware);

//store info on site usage- log with ID if userRoute
app.use('/', basic_routes.engagementMiddleware);

// bundle our user routes
var userRoutes = express.Router();
app.use('/user', userRoutes);


userRoutes.post('/upload', uploads:q, function(req,res){
    res.status(204).end("File uploaded.");
});

// Start the server
app.listen(port);

routes / basic_routes.js(跟踪参与中间件)

var db   = require('../config/database')
, jwt    = require('jwt-simple')
, getIP  = require('ipware')().get_ip
, secret = require('../config/secret').secret;


exports.engagementMiddleware = function(req, res, next){

    if (typeof(req.user) == 'undefined') req.user = {};

    var postData = {};
    var ip = getIP(req).clientIp;
    var fullUrl = req.protocol + '://' + req.get('host') + req.originalUrl;

    if (req.method=="POST") postData = req.body;

    var newEngagement = new db.engagementModel({
    user_id: req.user._id,
    ipAddress: ip,
    url: fullUrl,
    action: req.method,
    postData: postData
    });
    //log the engagement
    newEngagement.save(function(err) {
    if (err) {
        console.log('ERROR: engagement middleware db write failed');
        next();
    }
    console.log('LOG: user ' + req.user._id +' from ipAddress: ' + ip + ': ' + req.method + ' ' + fullUrl);
    next();
    });

    next();
}

config / passport.js(护照认证中间件)

var JwtStrategy = require('passport-jwt').Strategy;

// load up the user model
var db = require('../config/database'); // get db config file
var secret = require('../config/secret').secret;

module.exports = function(passport) {
var opts = {};
opts.secretOrKey = secret;
passport.use(new JwtStrategy(opts, function(jwt_payload, done) {
    db.userModel.findOne({id: jwt_payload.id}, function(err, user) {
        if (err) {
            return done(err, false);
        }
        if (user) {
            done(null, user);
        } else {
            done(null, false);
        }
    });
}));
};

routes / user_routes.js(用户路由中间件,用户添加到标头)

var jwt = require('jwt-simple');
var db    = require('../config/database');
var secret = require('../config/secret').secret;

//expose decoded userModel entry to further routes at req.user
exports.middleware = function(req, res, next){

var token = getToken(req.headers);
if (token) req.user = jwt.decode(token, secret);
else res.json({success: false, msg: 'unable to decode token'});

//should be unnecessary, double checking- after token verification against db
db.userModel.findOne({email: req.user.email}, function (err, user) {
    if( err || !user ) {
        console.log('something has gone horribly wrong. Token good, no user in db or access to db.');
        return res.status(403).send({success: false, msg: 'unable to find user in db'});
    }
});
//end unnecessary bit

next();
}


//helper function
getToken = function (headers) {
if (headers && headers.authorization) {

    var parted = headers.authorization.split(' ');
    if (parted.length === 2) return parted[1];
    else return null;

} else { return null; }
};

config / uploads.js(最后我们尝试上传的地方)

var moment = require('moment');
var multer = require('multer');
var jwt = require('jwt-simple');

var uploadFile = multer({dest: "audioUploads/"}).any();

var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, 'audioUploads/')
    },
    filename: function (req, file, cb) {
        cb(null, req.user._id + '_' + moment().format('MMDDYY[_]HHmm') + '.wav')
    }
});

exports.uploads = multer({storage:storage}).any();

1 个答案:

答案 0 :(得分:0)

在server.js中执行以下操作:

const authWare = passport.authenticate('jwt', {session:false});

userRoutes.post('/upload', authWare, uploads:q, function(req,res){
    res.status(204).end("File uploaded.");
});

为我工作!