I'm working on express js app and the first page is a login / register page. in login.js I have used passport and JWT to authenticate the user and redirect the successfully logged in user to the main page of the application:
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 });
});
});
}
for mypage route in the express I have
app.get('/mypage', (req, res) => {
res.sendFile(path.join(__dirname + '/view/mypage.html'));
}
});
it works but the problem is even not logged in users can access that route via localhost:PORT/mypage.
first, is redirecting to another route is the way to go? what is the best and approporiate way to redirect to another rendered page after successful login?
Add a middleware guard that checks if the request actually contains a token in its header.
Here's a generic example:
/* ================================================
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();
}
});
}
});