dll dll - 1 month ago 12
HTML Question

expressjs: how to use authentication function in another file attached to server.js?

Imagine that I have the following piece of code in server.js

function checkAuth(req, res, next) {
if (!req.session.user_id) {
res.sendFile(__dirname + '/login.html');
} else {
next();
}
}
app.get('/', (req, res) => {
res.sendfile(__dirname + 'login.html');
});
app.post("/login", (req, res) => {
if (req.body.userID === 'a' && req.body.password === 'b') {
req.session.user_id = req.body.userID;
res.redirect('main');
} else {
res.redirect('/');
}
});
app.get('/main', checkAuth, (req, res) => {
res.sendFile(__dirname + '/main.html');
});
app.get('/logout', (req, res) => {
delete req.session.user_id;
res.redirect('/');
});

require('./latestNews.js')(app);
require('./featuredNews.js')(app);

app.get('*', (req, res) => {
res.sendFile(__dirname + '/404.html');
});
app.listen(port, () => {
console.log("listening on " + port);
});


The user will first see the login page. Once he has logged in he can see the main page. Function checkAuth is used in app.get('/main',... in order to achieve this.

I attached two other files latestNews.js and featuredNews.js. Those includes also app.get, app.post, ... functions and looks like this:

module.exports = function(app){
app.get("/latestNews", (req, res) => {
res.sendFile(__dirname + '/latestNews.html');
});
}


Those are thus exported as modules and added to server.js as follows:

require('./latestNews.js')(app);
require('./featuredNews.js')(app);


I made a server.js, latestNews.js and featuredNews.js in order to separate the work and keep the code short instead of one long file.

My problem is now as follows:

How can I pass the 'checkAuth' function to the latestNews.js and featuredNews.js So I can use it like this ?

app.get("/latestNews", checkAuth (req, res) => {
res.sendfile(__dirname + '/latestNews.html');
});

Answer

You can create a new Router that has this check and is mounted to your app :

authorizedRouter = express.Router();

authorizedRouter.use( checkAuth );

app.use( '/', authorizedRouter );

require('./latestNews.js')(authorizedRouter);
require('./featuredNews.js')(authorizedRouter);

Just be careful where you mount your router. If you want to mount it at the / of your app, you should put it after all of your app.get/app.post declarations.

Comments