Ajout du dossier 'middlewares'
This commit is contained in:
@@ -62,5 +62,3 @@ sonar.properties
|
|||||||
**/*.copy.ts
|
**/*.copy.ts
|
||||||
**/*.copy.scss
|
**/*.copy.scss
|
||||||
**/*.copy.html
|
**/*.copy.html
|
||||||
|
|
||||||
middlewares
|
|
||||||
|
|||||||
@@ -0,0 +1,7 @@
|
|||||||
|
const asyncHandler = (fn) => (req, res, next) => {
|
||||||
|
Promise.resolve(fn(req, res, next)).catch((err) => {
|
||||||
|
next(err);
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
module.exports = asyncHandler;
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
const { verify } = require("../util/jwt");
|
||||||
|
const User = require("../models/User");
|
||||||
|
const ErrorResponse = require("../util/errorResponse");
|
||||||
|
|
||||||
|
exports.protect = async (req, res, next) => {
|
||||||
|
try {
|
||||||
|
const { headers } = req;
|
||||||
|
if (!headers.authorization) return next();
|
||||||
|
|
||||||
|
const token = headers.authorization.split(" ")[1];
|
||||||
|
if (!token) throw new SyntaxError("Token missing or malformed");
|
||||||
|
|
||||||
|
const userVerified = await verify(token);
|
||||||
|
if (!userVerified) throw new Error("Invalid Token");
|
||||||
|
|
||||||
|
req.loggedUser = await User.findOne({
|
||||||
|
attributes: { exclude: ["email", "password"] },
|
||||||
|
where: { email: userVerified.email },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!req.loggedUser) next(new NotFoundError("User"));
|
||||||
|
|
||||||
|
headers.email = userVerified.email;
|
||||||
|
req.loggedUser.dataValues.token = token;
|
||||||
|
|
||||||
|
next();
|
||||||
|
} catch (error) {
|
||||||
|
next(error);
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
const ErrorResponse = require("../util/errorResponse");
|
||||||
|
|
||||||
|
//REQUESTED PAGE IS NOT FOUND
|
||||||
|
module.exports.notFound = (req, res, next) => {
|
||||||
|
const error = new ErrorResponse(`Not Found - ${req.originalUrl}`);
|
||||||
|
res.status(404);
|
||||||
|
next(error);
|
||||||
|
};
|
||||||
|
|
||||||
|
module.exports.errorHandler = (err, req, res, next) => {
|
||||||
|
// Log to console for dev
|
||||||
|
console.log(err.message.red);
|
||||||
|
console.log(err.stack.red);
|
||||||
|
|
||||||
|
const statusCode = err.statusCode ? err.statusCode : 500;
|
||||||
|
|
||||||
|
res.status(statusCode).json({
|
||||||
|
errors: {
|
||||||
|
body: [err.message],
|
||||||
|
},
|
||||||
|
});
|
||||||
|
};
|
||||||
Reference in New Issue
Block a user