This repository has been archived on 2024-10-29. You can view files and clone it, but cannot push or open issues or pull requests.
FunctionProject/api/middlewares/isAuth.js

34 lines
855 B
JavaScript
Raw Normal View History

2020-08-03 12:04:07 +02:00
const jwt = require('jsonwebtoken')
const errorHandling = require('../assets/utils/errorHandling')
const { JWT_SECRET } = require('../assets/config/config')
2020-03-25 16:23:43 +01:00
module.exports = (req, _res, next) => {
2020-08-03 12:04:07 +02:00
const token = req.get('Authorization')
if (!token) {
2020-08-03 14:14:45 +02:00
return errorHandling(next, {
message: 'Vous devez être connecter pour effectuer cette opération.',
statusCode: 403
})
2020-08-03 12:04:07 +02:00
}
2020-03-25 16:23:43 +01:00
2020-08-03 12:04:07 +02:00
let decodedToken
try {
decodedToken = jwt.verify(token, JWT_SECRET)
} catch (error) {
2020-08-03 14:14:45 +02:00
return errorHandling(next, {
message: 'Vous devez être connecter pour effectuer cette opération.',
statusCode: 403
})
2020-08-03 12:04:07 +02:00
}
2020-03-25 16:23:43 +01:00
2020-08-03 12:04:07 +02:00
if (!decodedToken) {
2020-08-03 14:14:45 +02:00
return errorHandling(next, {
message: 'Vous devez être connecter pour effectuer cette opération.',
statusCode: 403
})
2020-08-03 12:04:07 +02:00
}
2020-03-25 16:23:43 +01:00
2020-08-03 12:04:07 +02:00
req.userId = decodedToken.userId
next()
}