Я пытаюсь передать User ID
в multer
функцию с именем upload
, чтобы я мог загрузить изображения с User ID
в качестве имени.
User ID
- это токен JWT
, который должен быть decoded
перед использованием.
Я хочу, чтобы функция authenticate
выполнялась первой, чтобы я мог передать User ID
в функцию upload
. но в действительности сначала выполняется upload
, а затем authenticate
, что означает, что я не могу проверить подлинность пользователя перед загрузкой файлов.
Upload
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, path)
},
filename: (req, file, cb) => {
// user ID fetched from the JWT cookie
console.log(req.user) // this should be the plaintext User ID if the authenticate function ran first.
req.myfiles = req.files // pass the file object to the next middleware
cb(null, `image.jpg`)
}
})
const fileFilter = (req, file, cb) => {
const mimeType = file.mimetype.toLowerCase()
console.log(file)
if (mimeType === 'image/jpeg' || mimeType === 'image/png') { // the uploaded file MUST be an image type
console.log('filter success')
cb(null, true)
}else {
console.log('file filter, failed')
cb(null, false) // reject if the uploaded file is not an image
}
}
authenticate
-
const FindByEmail = async (jwt_payload, done) => {
// search for the user's ID by their email
try {
const email = jwt_payload.subject
request.input('email', email )
await request.execute('isAuthenticated', (err, docs) => {
if (err || docs.rowsAffected < 1) return done(err, false)
console.log('fired..')
return done(null, docs.recordset[0].ID) // send the User ID to the next middleware which in this case is Upload function
})
} catch (err) {
return done(err, false)
}
}
const cookieExtractor = (req) => req.cookies['jWtToken']
JWT_OPTIONS = {
jwtFromRequest: cookieExtractor,
secretOrKey: JWT_SALT
}
module.exports = {
authenticate: passport.authenticate('jwt', {
session: false
}),
JWT_OPTIONS,
JwtStrategy,
FindByEmail
}
app.post('/image', authenticate, upload, (req,res)=> console.log(req.body))