btmach btmach - 5 months ago 8
Javascript Question

Securing a specific route node.js

Hey I'm using basic auth for Node.JS to secure a route. I'm pretty new to Node.JS and don't understand what the next function does in this case. What I'm trying to do is to secure a the route:

/admin/


Note: This is a project for learning purposes so the login part is not too serious and won't be used live.

authentication.js

var basicAuth = require('basic-auth');

exports.BasicAuthentication = function(request, response, next) {

function unauthorized(response) {
response.set('WWW-Authenticate', 'Basic realm=Authorization Required');
return response.send(401);
};

var user = basicAuth(request);

if (!user || !user.name || !user.pass) {
return unauthorized(response);
};

if (user.name === 'name' && user.pass === 'pass') {
return next();
} else {
return unauthorized(response);
};

};


and app.js where I imported the module authentication:

app.get('/admin/', authentication.BasicAuthentication, function(req, res){
console.log("hi u need to login");
});


So what I want to do is to route the user further if the authentication goes through.

Thanks in advance!

Answer

Try:

app.get('/admin/', authentication.BasicAuthentication);
app.get('/admin/', function(req, res) {});
Comments