Express Returning After next() - express

came from Java. Was messing around with ExpressJS, I return out of a function after sending a next() if I dont add the return, then code after the next() function still executes when next() is invoked, currently it works, return escapes this behaviour, but I was wondering if this is correct way to do this, or am I developing bad habbits. Nothing is really after the next() in terms of code sequence.
function('/login', (req,res, next) => {
User.findOne({
email: username
}, (err, user) => {
if (user) {
var validPassword = user.comparePassword(password);
if (validPassword) {
let token = Helpers.getJwt(user);
res.send({
success: true,
message: 'Successful Login',
token: token
})
} else {
next(
Boom.badRequest('Invalid Credentials.', {
success: false,
message: 'Credentials did not match our records.'
}));
return;
}
} else {
next(
Boom.badRequest('User not found.', {
success: false,
message: 'User was not found, please register.'
}));
return;
}
});
EDIT: I have middleware called with the next(), my error middleware.

First, You aren't next-ing to anything here(pun intended).
You call middleware:next() function if there is another middleware:function within the chain of a particular route or a group of routes app.use(middleware:function).
Example:
app.get('/user/:id', function (req, res, next) {
console.log('ID:', req.params.id)
next()
}, function (req, res, next) {
res.send('User Info')
})
I'd advice you read on Express Middlewares.
so yeah, you want to check if the user is valid before proceeding with the request.
Below code is just to explain how middle-ware works:
The idea is that, one middleware:function process the request and passes control down to the next function within the chain.
I'm assuming your Boom.badRequest just generates a json payload e.g {};
So this is probably an elegant way to achieve what you want, but im not sure doing this for login is ideal, maybe better for checking if a user's token is valid.
app.post('/login', /*MiddleWare Function*/(req, res, next) => {
User.findOne({email: username}, (err, user) => {
if (user) {
const validPassword = user.comparePassword(req.body.password);
if (!validPassword) return res.status(401).send(Boom.badRequest('User not found.', {
success: false,
message: 'User was not found, please register.'
}));
req.token = Helpers.getJwt(user);
next();// it will move execution to the next function we have below
} else {
res.status(401).send(Boom.badRequest('User not found.', {
success: false,
message: 'User was not found, please register.'
}));
//no need to next here.
}
})
}, /*OUR NEXT FUNCTION*/(req, res) => {
res.send({
success: true,
message: 'Successful Login',
token: req.token//notice that our token can be retrieved here
})
});
So in general, you might just want to have a middleware:function that is called first on a group of specific routes.
app.use(['/users*', '/logout'], (req, res, next) => {
/*
* What this means is that for every request that maps to /users
* or /logout this middleware:function will be called first.
*/
//we can check|test if this visitor has valid credentials.
next();//passes control to app.get('/users/whatEverItIS?') or app.post('/logout');
});
app.post('/users/whatEverItIs', (req, res)=>{
res.send("I passed the middleware test that is why im called");
});

That return statement is unnecessary. Firstly due to the fact that you are not returning anything and secondly because you are passing control to your next middleware using next method, thus that return is useless there and will be returning undefined.

Related

Callback function 'next' is executed automatically without making a call to it

I have this POST method which uses FetchURL middleware to fetch data from the url submitted by the user.
router.post('/', FetchURL, (req, res) => {
console.info('data received');
...
})
Everything works with response.ok being true, but the contrary case doesn't quite work as expected.
I don't want next to be called when response.ok equals false.
But I get to see "data received" logged to the console which means the next function does get called on its own.
fetch_url.js
function FetchURL(req, res, next) {
fetch(req.body.input_url)
.then(response => {
if(response.ok)
return response.json();
// else render error message on the client machine
res.status(response.status)
.render('index', {
errStatus: [response.status, response.statusText]
});
/* Throwing an Error here is the only way I could prevent the next callback */
// throw new Error(`Request failed with status code ${response.status}.`);
})
.then(data => {
req.data = data;
next();
})
.catch(err => console.error(err));
}
I could not find anything relevant on the documentation of expressjs middleware. The only way I could prevent next from being called is by throwing an Error on the server.
What happens behind the scene here?
try making a second check before next is called like following
function FetchURL(req, res, next) {
fetch(req.body.input_url)
.then(response => {
if(response.ok) // wrap your response in a temporary object.
return { fail: false, data: response.json() } ;
// else render error message on the client machine
res.status(response.status)
.render('index', {
errStatus: [response.status, response.statusText]
});
/* Instead of throwing an Error, return something indicating error */
return { fail: true };
})
.then(data => {
// check if previous procedure has failed.
if(!data.fail) {
req.data = data.data;
next();
}
})
.catch(err => console.error(err));
}

app.get with multiple arguments - e.g. app.get('/', requireAuth, (req, res) => { })

I am wondering how express.js works when you specify multiple argument in the app.get, for example:
app.get('/', requireAuth, (req, res) => { })
Here, I believe you have the slash "/" as the route, and (req, res) as arguments for the callback function. But there is also the 'requireAuth' part which was used for authorization. But in the documentation I don't find anything about multiple arguments in the way we use 'requireAuth' now. It does mention that you can use an array of functions but that is not used here (https://expressjs.com/en/guide/routing.html). How does it work?
P.S. The 'requireAuth' code for reference:
module.exports = (req, res, next) => {
const { authorization } = req.headers;
// authorization === 'Bearer laksjdflaksdjasdfklj'
if (!authorization) {
return res.status(401).send({ error: 'You must be logged in.' });
}
const token = authorization.replace('Bearer ', '');
jwt.verify(token, 'MY_SECRET_KEY', async (err, payload) => {
if (err) {
return res.status(401).send({ error: 'You must be logged in.' });
}
const { userId } = payload;
const user = await User.findById(userId);
req.user = user;
next();
});
};
All the arguments are simply middle-ware functions that you call before the actual route logic is run(for individual routes). As long as there is next handling in each of the middle-ware functions, the chain will run till your route logic, and then exit where next isn't handled.
This is the magic of express. You can do many things with it, like error handling, handling different content types etc.

Cookie blocked by Chrome

I am trying to set up a simple register/login form with vuejs in the front and a server with express js using the passport library to setup a local and social media startegy.
But I can't seem to pass cookies to the front end when I login with the local strategy.
Also when I sign in with google I get the cookie on the front end but it is not sent with the next API call but this is a subject for another question.
I was confused by this so I made a simple project just to receive and send cookies and it works. Here is the back end:
//headers in app.js
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', 'http://localhost:8080');
res.header('Access-Control-Allow-Credentials', true);
res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, DELETE');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
next();
});
// index file
router.get('/cookie', function (req, res, next) {
res.cookie("token", "mytoken");
res.send("cookie sent");
});
router.get('/info', function (req, res, next) {
cookies = req.cookies;
console.log(cookies);
res.cookie("token", "mytoken");
res.send("cookie sent");
});
And here is my front end methods that call the API:
methods: {
async getCookie() {
await axios.get("http://localhost:3000/cookie",{withCredentials:true}).then((response) => {
console.log(response);
}).catch((e) => {
console.log(e);
});
},
async sendCookie() {
await axios.get("http://localhost:3000/info",{withCredentials:true}).then((response) => {
console.log(response);
}).catch((e) => {
console.log(e);
});
}
}
With that I have no problem passing the cookie in the requests and receiving it.
Now on my real project I have this on the back end
//Headers just like the other project
router.post('/users/login', function (req, res, next) {
passport.authenticate('local', { session: false }, function (err, user, info) {
if (err) { return next(err); }
if (user) {
res.cookie('token', 'mytoken');
return res.json({ user: user.toAuthJSON() });
} else {
return res.status(401).json(info);
}
})(req, res, next);
});
Front end call:
// Service file to call the api
axios.defaults.baseURL = "http://127.0.0.1:3000/api/";
axios.defaults.withCredentials = true;
const ApiService = {
get(resource, slug = "") {
return axios.get(`${resource}/${slug}`).catch(error => {
throw new Error(`ApiService ${error}`);
});
},
...
}
export default ApiService;
//actual call in authetification module file
[LOGIN](context, credentials) {
return new Promise(resolve => {
ApiService.post("users/login", { email: credentials.email, password: credentials.password })
.then(({ data }) => {
context.commit(SET_AUTH, data.user);
resolve(data);
})
.catch(({ response }) => {
context.commit(SET_ERROR, response.data.errors);
});
});
},
//
The request works but the cookie is blocked by Chrome:
I don't see what is the difference in my two projects that would trigger this warning on Chrome for the last one.
EDIT: In my original post axios.defaults.baseURL was not set to my actual value.
After last update of chrome browser I also started to get this error. A solution to solve this go to chrome://flags and disable SameSite by default cookies and disable Enable removing SameSite=None cookies. This will solve your problem. I think another way to solve this changing your cookie settings(samesite attribute) when you are creating your session.
Find the solution thank to #skirtle. I set axios.defaults.baseURL to "http://127.0.0.1:3000/api/" but localhost and 127.0.0.1 are not interchangeable and considered two different domains. I switched to axios.defaults.baseURL = "http://localhost:3000/api" and it fixed the problem.

Nuxtjs - Authentication

I wrote a sign up functionality in nuxtjs. It saves a new user in my database. However, there seems to be a problem with generating a token afterwards, to log in the user.
The register action gets called by a method in the register component. It returns the error response in the catch block. It seems to fail after the token is generated on the server.
Action in the store
async register ({ commit }, { name, slug, email, password }) {
try {
const { data } = await this.$axios.post('/users', { name, slug, email, password })
commit('SET_USER', data)
} catch (err) {
commit('base/SET_ERROR', err.response, { root: true })
throw err
}
}
Post function on the nodejs server
router.post('/users', async (req, res) => {
try {
const body = _.pick(req.body, ['name', 'slug', 'email', 'password']);
const user = new User(body);
await user.save();
const token = await user.generateAuthToken(); // execution seems to fail on this line
console.log(token); // never gets called
req.session['token'] = 'Bearer ' + token;
req.session['user'] = user;
res.header('Authorization', 'Bearer ' + token).send(user);
} catch (err) {
res.status(400).json({ message: "Der Account konnte leider nicht erstellt werden" });
}
});
GenerateAuthToken function in mongo model User
UserSchema.methods.generateAuthToken = function () {
var user = this;
var access = 'auth';
var token = jwt.sign({_id: user._id.toHexString(), access}, process.env.JWT_SECRET).toString();
user.tokens.push({access, token});
return user.save().then(() => {
return token;
});
};
Error message
I would be tremendously thankful for any kind of help!
Maybe it doesn't help too much, but I would try to create a dummy token and try to make everything works with it. One of my debugging techniques is to isolate every single part of my code and be sure that everything works piece for piece, maybe that technique is slow but most of the time it works.
If everything works, I would continue debugging the generateAuthToken function.
If your console log never gets called, then the error could be in the function.
I hope it helps a little and sorry I don't know too much about MongoDB but everything seems to be ok.

Express Passportjs Authenticate not being reached in router callback

If I pass passport.authenticate("local") as middleware into my route, it executes. But this way I do not have access to res so I can send a message back to my front end. However, if I attempt to call it in the route callback function, it is not firing.
router.post("/login", function(req, res, next) {
passport.authenticate("local", function(err, user, info) {
console.log("Unreached"); // This is not logging
});
})
Here is my passport.use inside app.js
passport.use(new LocalStrategy({
usernameField: "portalId"
}, function(portalId, enteredPassword, done) {
var params = {
TableName: "MyTableName",
KeyConditionExpression : "PortalID = :portalID",
ExpressionAttributeValues : {
":portalID" : Number(portalId)
}
}
docClient.query(params, function(err, user) {
if (err) throw err;
let realPassword = user.Items[0].password;
bcrypt.compare(enteredPassword, realPassword, function(err, res) {
if (err) throw err;
if (res) {
return done(null, user);
}
if (!res) {
return done(null, false, { message: "Invalid Credentials" });
}
})
})
}));
Saw in some other post a snippet of code using the custom callback and he had (req, res, next) right after the passport.authenticate function. I added this and my code was being fired now.