Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

257
Views
Redirigir la ruta express js después de un inicio de sesión exitoso

Estoy trabajando en la aplicación express js y la primera página es una página de inicio de sesión/registro. en login.js he usado passport y JWT para autenticar al usuario y redirigir al usuario que inició sesión correctamente a la página principal de la aplicación:

 function login(req, res, next){ User.forge({ email: req.body.email }).fetch().then(result => { if (!result) { return res.status(401).send('user not found'); } result.authenticate(req.body.password).then(user => { const payload = { id: user.id }; const token = jwt.sign(payload, process.env.SECRET_OR_KEY); console.log(res.statusCode); // just for testing res.redirect('/mypage'); }).catch(err => { return res.status(401).send({ err: err }); }); }); }

para ruta mypage en el express tengo

 app.get('/mypage', (req, res) => { res.sendFile(path.join(__dirname + '/view/mypage.html')); } });

funciona, pero el problema es que incluso los usuarios que no han iniciado sesión pueden acceder a esa ruta a través de localhost:PORT/mypage .

primero, ¿es redirigir a otra ruta el camino a seguir? ¿Cuál es la mejor y más adecuada forma de redirigir a otra página renderizada después de iniciar sesión correctamente?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Agregue un protector de middleware que verifique si la solicitud realmente contiene un token en su encabezado.

He aquí un ejemplo genérico:

 /* ================================================ INFO: @MIDDLEWARE - Used to grab user's token from headers ================================================ */ router.use((req, res, next) => { // INFO: Getting the generated token from headers const token = req.headers['authorization']; // Create token found in headers // INFO: Check if token was found in headers if (!token) { let content = `<body style="margin: 0px;"> <div style="width: -webkit-fill-available; height: -webkit-fill-available;"> <div class="col-sm-12 " style="padding-top: 1em; padding-left: 1em;"> <h3 style="color:#666666;">Direct navigation via the browser's URL-bar forbidden!</h3> <p style="color:#666666;">Please use the navigation provided by the application only.</p> <a style="color:#800101; text-decoration:none; font-weight:bold;" href="http://${stdoutIP}" target="_self">Back to Login</a> </div> </div> </body>`; res.send(content); } else { // INFO: Verify the token is valid jwt.verify(token, "myVerySecretSecret", (err, decoded) => { // INFO: Check if error is expired or invalid //console.log("token verification:",token); if (err) { // INFO: Return error for token validation res.json({ success: false, message: 'Token invalid: ' + err }); } else { // INFO: Create global variable to use in any request beyond req.decoded = decoded; // INFO: Exit middleware next(); } }); } });
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!