首页 > 解决方案 > 如果凭据错误,我将如何将用户重定向回主页?

问题描述

所以我的 expressJS 应用程序有问题。我将其用于基本授权,因此不是每个人都可以添加、删除或更新数据库中的数据。

我想要做的是,如果用户插入正确的密码和用户名,他就可以访问该页面。这对我有用。但是,如果凭据错误,或者凭据尚未填写,则应将他重定向回主页。

到目前为止我的代码是这个获取请求......但是我如何让用户重定向到主页,而不是显示未经授权。

router.get(
  '/bikepart/create',
  authenticatorFn,
  bikepartController.bikepart_create_get
);

的代码getUnauthorizedResponse是:

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();
  }
}

这也是我的代码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,
      });
    }
  );
};

那么如果有未经授权的响应,我将如何将用户重定向到主页?我在这里有点迷路了。

标签: javascriptnode.jsexpressauthentication

解决方案


推荐阅读