I have set up a web application with some internal pages requiring a login. I used Node with Express.js to set up the server and controlling the routes and authentication wo
You can create a new module called auth.js
and then use it to check if users are authorized or not:
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();
}
}
});
}
routes.js
var auth = require('./auth');
// GET route after registering
router.get('/clientPage', auth.isAuthorized, function (req, res, next) {
res.sendFile(path.join(__dirname + '/../views/clientPage.html'));
});
Create a module (a file that exports a function, in this case a middleware function). A middleware function has following signature function (req, res, next) { .... }
restrict.js
module.exports = function (req, res, next) {
User.findById(req.session.userId)
.exec(function (error, user) {
if (error) {
return next(error);
} else {
if (user === null) {
const err = new Error("Not authorized! Go back!");
err.status = 400;
return next(err); // This will be caught by error handler
} else {
return next(); // No error proceed to next middleware
}
}
});
};
app.js
// serve static files from template
app.use(express.static(__dirname + '/public'));
// include routes
const routes = require('./routes/router');
//If you have a more granular route you can split it
const someOtherRoute = require('./routes/someotherRoute');
const restrictMiddleware = require("./restrict");
app.use("/", someOtherRoute); // this route will not be check for authorization
app.use(restrictMiddleware);
app.use('/', routes);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
const err = new Error('File Not Found');
err.status = 404;
next(err);
});
// error handler
// define as the last app.use callback
app.use(function (err, req, res, next) {
res.status(err.status || 500);
res.send(err.message);
});
I would use const
and let
if your environment support it. Its 2017 :)