Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS fill "req" from other function

I've got a NodeJS + Express Server setup with a router that looks like this:

app.route('/clients/:clientId)
    .get(users.ensureAuthenticated, clients.read)
    .put(users.ensureAuthenticated, clients.hasAuthorization, clients.update)
    .delete(users.ensureAuthenticated, clients.hasAuthorization, clients.delete);

app.param('clientId', clients.clientByID);

My Problem is that users.ensureAuthenticated fills the req parameter with the current user req.user.

Basically it does this: req.user = payload.sub; (with some other background stuff)

Then the req.user is available in the following functions e.g. clients.update, but not in clients.clientByID.

I know I could execute users.ensureAuthenticated in clients.clientByID again, but this would execute the code twice and be extra load on the server, right? I guess there must be another way, but I couldn't find anything in the documentation of express.

I'd like to know how I can access the req.user in clients.clientByID without executing the code in users.ensureAuthenticated twice.

like image 714
EinArzt Avatar asked Sep 04 '26 23:09

EinArzt


1 Answers

Based on your question, I assume you would like to execute users.ensureAuthenticated before clients.clientByID is executed. This can be achieved by using the app.use functionality. app.use handlers will get executed before the app.param and app.route handlers.

For example:

var express = require('express');
var app = express();

app.use('/user', function(req, res, next) {
    console.log('First! Time to do some authentication!');
    next();
});

app.param('id', function(req, res, next, id) {
    console.log('Second! Now we can lookup the actual user.');
    next();
});

app.get('/user/:id', function(req, res, next) {
    console.log('Third! Here we do all our other stuff.');
    next();
});

app.listen(3000, function() {
});
like image 182
xaviert Avatar answered Sep 07 '26 12:09

xaviert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!