I've recently switched to Cognito for the authentication on my website. I'm using NodeJS/Express to run the server. With each API call having a callback in between the declaration and the main function to check the if the user is authenticated, currentAuthenticatedUser(), this should return a cognito user object for the current req/session.
What I've found is that this function works fine until someone logs in. If I log in like normal, my account then becomes authenticated, I gain access to the main page etc.
But then if I send someone else the website link, they automatically bypass the login because this function returns my user object, as opposed to filtering by request or session and replying with not authenticated. This seems like too basic of an issue to be right, in the sense that the Amplify function will return the user object of whoever is the last to sign in and authenticate, regardless of the auth status of any new incoming requests from elsewhere.
The two auth checks:
function checkAuthenticated(req, res, next) {
auth.currentAuthenticatedUser()
.then(user => {
console.log(user);
next();
})
.catch(err => {
console.log(err);
return res.redirect('/login');
});
}
function checkNotAuthenticated(req, res, next) {
auth.currentAuthenticatedUser()
.then(user => {
console.log(user);
return res.redirect('/');
})
.catch(err => {
console.log(err);
next();
});
}
Examples of API calls:
app.get('/', checkAuthenticated, (req, res) => {
res.render('index.ejs');
});
app.post('/login', checkNotAuthenticated, async (req, res, next) => {
// Some code to login
});
Any guidance is appreciated.