So I am having a problem in my expressJS app. I am using this for basic authorization, so that not everyone can add, delete or update the data in database.
What I am trying to do is, if the user inserts the correct password and username it gives him access to the page. This works for me. But if credentials are wrong, or the credentials haven't been filled it should redirect him back to the homepage.
The code I have so far is this get request... but how would I make user redirect to home page, instead of showing unauthorized.
router.get(
'/bikepart/create',
authenticatorFn,
bikepartController.bikepart_create_get
);
The code of getUnauthorizedResponse
is:
function authenticatorFn(req, res, next) {
var auth;
// check whether an autorization header was send
if (req.headers.authorization) {
auth = new Buffer(req.headers.authorization.substring(6), 'base64')
.toString()
.split(':');
}
if (!auth || auth[0] !== 'testuser' || auth[1] !== 'testpassword') {
// any of the tests failed
// send an Basic Auth request (HTTP Code: 401 Unauthorized)
res.statusCode = 401;
// MyRealmName can be changed to anything, will be prompted to the user
res.setHeader('WWW-Authenticate', 'Basic realm="MyRealmName"');
// this will displayed in the browser when authorization is cancelled
res.end('Unauthorized');
} else {
// continue with processing, user was authenticated
next();
}
}
And here is also my code for bikepart_create_get
:
exports.bikepart_create_get = function (req, res, next) {
async.parallel(
{
manufacturers: function (callback) {
Manufacturer.find(callback);
},
categories: function (callback) {
Category.find(callback);
},
},
function (err, results) {
if (err) {
return next(err);
}
res.render('bikepart_form', {
title: 'Create new bikepart',
categories: results.categories,
manufacturers: results.manufacturers,
});
}
);
};
So how would I redirect user to homepage if there is unauthorized response? I'm a bit lost here.