freeCodeCamp/curriculum/challenges/chinese/06-information-security-and.../advanced-node-and-express/create-new-middleware.chine...

2.8 KiB
Raw Blame History

id title challengeType videoUrl localeTitle
5895f70df9fc0f352b528e6a Create New Middleware 2 创建新的中间件

Description

提醒一下,这个项目是基于Glitch的以下入门项目构建的,或者是从GitHub克隆的。同样,任何用户都可以通过输入网址来查看/配置他们是否通过身份验证。我们希望通过在呈现配置文件页面之前检查用户是否首先进行身份验证来防止这种情况。这是何时创建中间件的完美示例。这里的挑战是创建中间件功能ensureAuthenticated(req, res, next) 它将检查用户是否通过调用护照进行身份验证isAuthenticated对请求进行检查,然后检查req.user是否定义。如果是,那么应该调用next ,否则我们只需通过重定向到我们的主页来回复请求即可登录。该中间件的实现是:
 function ensureAuthenticatedreqresnext{
  ifreq.isAuthenticated{
      return next;
  }
  res.redirect '/';
}; 
现在在包含呈现页面的函数的get请求的参数之前ensureAuthenticated作为中间件添加到配置文件页面的请求中。
 app.route '/简档'
  .getensureAuthenticatedreqres=> {
       res.renderprocess.cwd+'/ views / pug / profile';
  }; 
当您认为自己已经做对时,请提交您的页面。

Instructions

Tests

tests:
  - text: 中间件确保应该在我们的/配置文件路由上实现
    testString: 'getUserInput => $.get(getUserInput("url")+ "/_api/server.js") .then(data => { assert.match(data, /ensureAuthenticated[^]*req.isAuthenticated/gi, "Your ensureAuthenticated middleware should be defined and utilize the req.isAuthenticated function"); assert.match(data, /profile[^]*get[^]*ensureAuthenticated/gi, "Your ensureAuthenticated middleware should be attached to the /profile route"); }, xhr => { throw new Error(xhr.statusText); })'
  - text: 正确的Get请求/配置文件重定向到/因为我们未经过身份验证
    testString: 'getUserInput => $.get(getUserInput("url")+ "/profile") .then(data => { assert.match(data, /Home page/gi, "An attempt to go to the profile at this point should redirect to the homepage since we are not logged in"); }, xhr => { throw new Error(xhr.statusText); })'

Challenge Seed

Solution

// solution required