I have a middleware function to do the basic authorization which is in app.js (starter javascript). But there are a few router files in other javascript files. My question is how I can call the authorization middleware function in my router?
Here is my app.js:
var basicAuth = require('basic-auth');
var auth = function (req, res, next) {
function unauthorized(res) {
res.set('WWW-Authenticate', 'Basic realm=Authorization Required');
return res.send(401);
};
var user = basicAuth(req);
if (!user || !user.name || !user.pass) {
return unauthorized(res);
};
if (user.name === 'foo' && user.pass === 'bar') {
return next();
} else {
return unauthorized(res);
};
};
module.exports = app;
My router file index.js:
var express = require('express');
var router = express.Router();
router.get('/', auth, function(req, res) {
res.render('index', { title: 'Express' });
});
module.exports = router;
Apparently the auth is not defined here. Can anybody tell me how can I use auth middleware function in my index.js router functions? Thanks
I'm not sure exactly what you're attempting to export with.
module.exports = app;
in app.js
Here is a simplifed solution:
index.js
var express = require('express');
var app = express();
var auth = require('./auth');
var router = express.Router();
router.use(auth); // Auth middleware is first
router.get('/', function(req, res) {
return res.send('Hello world');
}
// More routes can go here
// require('./external')(router);
// router.get('/route', function(req, res) {}
app.use(router);
app.listen(3000);
auth.js
module.exports = function(req, res, next) {
return next();
}
If you have routes in other files you can either pass app or router
external.js
module.exports = function(router) {
}
Why not put your auth middleware in a separate file that you can require() and use from both app.js and your router files?