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

3.0 KiB

id title localeTitle challengeType
5895f70df9fc0f352b528e6a Create New Middleware Crear nuevo middleware 2

Description

Como recordatorio, este proyecto se está construyendo sobre el siguiente proyecto de inicio en Glitch , o clonado desde GitHub . Al igual que en, cualquier usuario puede simplemente ir a / profile si se autenticaron o no escribiendo la url. Queremos evitarlo comprobando si el usuario se autentica primero antes de representar la página de perfil. Este es el ejemplo perfecto de cuándo crear un middleware. El desafío aquí es crear la función de middleware ensureAuthenticated(req, res, next) , que verificará si un usuario se autentica llamando a los pasaportes autenticados en la solicitud, que a su vez verifica si es necesario definir el usuario . Si es así, se debe llamar a next () , de lo contrario, solo podemos responder a la solicitud con un redireccionamiento a nuestra página de inicio para iniciar sesión. Una implementación de este middleware es:
 la función garantizarAutenticada (req, res, next) { 
if (req.isAuthenticated ()) { 
return next (); 
} 
res.redirect ('/'); 
}; 
Ahora agregue asegúrese de Autentificado como un middleware a la solicitud de la página de perfil antes del argumento a la solicitud de obtención que contiene la función que representa la página.
 app.route ('/ profile') 
.get (asegurarAuthenticated, (req, res) => { 
res.render (process.cwd () + '/ views / pug / profile'); 
}); 
Envía tu página cuando creas que lo has hecho bien.

Instructions

Tests

tests:
  - text: Middleware asegurarAutenticado debe implementarse y en nuestra ruta / perfil
    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: Una solicitud de obtención a / perfil redirige correctamente a / ya que no estamos autenticados
    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