1

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.

Emilija
  • 89
  • 7
  • 2
    I'm not sure whether `express-basic-auth` supports this at all, but a workaround is something similar to this [post](https://stackoverflow.com/questions/24283848/express-basicauth-throwing-error), which handles authentication/authorization in API functions and you can write 302 redirect response in it. – Mohammad Moallemi Feb 18 '21 at 08:27
  • 1
    So basically I am at the part, I managed to make it work, but if I put the `res.redirect("/")`instead of `res.end()`... it doesnt even show me the pop up for inserting username and password. – Emilija Feb 18 '21 at 16:37

0 Answers0