CascadiaJS CascadiaJS - 27 days ago 16
Javascript Question

Express response not executing in Sequelize catch handler

I am using passport and OAuth to authenticate users on my site. I have made middleware to check if a user logged in with OAuth and if they are on a list of allowed users. The middleware works and prevents users from accessing the data routes where it is used if they aren't authorized. The issue is that the response is never being called in the Sequelize

catch
handler after it fails to find the user in the list, so they're never redirected if it fails and it just shows the page with no data.

Here is my middleware. I know that the
catch
is being reached, because I can see the console.log, but the
res.status('401').redirect(
/admin/login
);
never happens. Let me know if there are other parts of the code that would be useful to see. Thanks in advance for all your help!



'use strict';
const clc = require(`cli-color`);
const models = require('../models');
const User = models.User;

function isLoggedIn(req, res, next) {
console.log(clc.red.bgBlue(` ::: `), req.user);
res.header('Access-Control-Allow-Credentials', true);
models.sql.sync()
.then(() => {
User.findOne({
where: {
email: req.user.unique_name
}
});
})
.then((user) => {
if (req.isAuthenticated() && user !== null && user.email === req.user.unique_name) { // if user is authenticated in the session and the user email matches the user found in the db, carry on
return next();
} else {
// if they aren't send not authorized
res.status('401').redirect(`/admin/login`);

}
})
.catch((err) => {
console.log(clc.red.bgWhite(`ERR :::: )`), err);
res.status(`401`).redirect(`/admin/login`);
});

}

module.exports = isLoggedIn;




Answer

According to docs correct syntax is:

res.redirect(401, 'http://example.com');

See also: Chaining Express.js 4's res.status(401) to a redirect