As the title suggests, I want to reduce duplicate authorization code for each new route I call. My problem is exactly the same as the user in this post, because apparently we downloaded the same project from GitHub repository.
I tried both of the solutions suggested in the answers, however it restricts me from accessing those routes even if I'm logged in.
Here's the code:
router.js
// GET route for reading data
router.get("/", function (req, res, next) {
return res.sendFile(path.join(__dirname + "/login"));
});
//Export authorization module
var auth = require("../auth");
//Verify if user is authorized to access this route
router.get("/complete-profile", auth.isAuthorized, function (req, res, next) {
return res.sendFile(path.join(__dirname, "../public", "image.html"));
});
//READ THE IMAGE UPLOAD FOLDER
router.use(express.static("public"));
// GET route after login, verify if user logged in
router.get("/complete-profile", function (req, res, next) {
User.findById(req.session.userId).exec(function (error, user) {
if (error) {
return next(error);
} else {
if (user === null) {
var err = new Error("Not authorized! Go back!");
err.status = 400;
return next(err);
} else {
//SEND NEW USERS TO IMAGE UPLOAD PAGE
return res.sendFile(path.join(__dirname, "../public", "image.html"));
}
}
});
});
As suggested, I tried declaring all of this as a middleware, so here is the middleware:
auth.js
module.exports.isAuthorized = function(req, res, next) {
User.findById(req.session.userId).exec(function (error, user) {
if (error) {
return next(error);
} else {
if (user === null) {
var err = new Error('Not authorized! Go back!');
err.status = 400;
return next(err);
} else {
return next();
}
}
});
}
Any help is gladly appreciated!
Source: How to setup an authentication middleware in Express.js