Katya S
Katya S

Reputation: 1363

NodeJS express basicAuth - how to pass username to the route function?

I've got a working node app where I need to connect to different DBs based on what user is connecting to the app via basicAuth.

Here's a sample:

// Authenticating function
var sgAuth = express.basicAuth(function(user, pass, callback){
  if(config.credentials.clients[user] === undefined) {
    callback(null, false);
  } else {
    callback(null, config.credentials.clients[user].password == pass);
  }
});

// This function needs to know what user has authenticated
function putEvents(req, res) {
    //How do I know what user authenticated in this request?
    var authUser = ???;
    var table = getUserTable(authUser);
    ...
}
app.post('/put', sgAuth, putEvents);

Storing username in sgAuth to some var surely won't work, because there can be many incoming connections from different users, so you can't guarantee that its the same user, right? Can this info be retrieved from the request header somehow?

Upvotes: 0

Views: 4044

Answers (2)

damphat
damphat

Reputation: 18956

Note that: basicAuth is deprecated

Here the code:

app.use(express.basicAuth(function(user, pass, callback){
  if(config.credentials.clients[user] === undefined) {
    callback('user not found!!!');
  } else {
    if(config.credentials.clients[user].password === pass) {
       callback(null, config.credentials.clients[user]);
    } else {
       callback('wrong pass!!!');
    }
  }
});

app.post('/put', function putEvents(req, res) {
   console.log(req.user.name) 
   res.end();
});

Upvotes: 0

Jonathan Lonowski
Jonathan Lonowski

Reputation: 123553

The basicAuth() middleware will set req.user and req.remoteUser once authorized.

Though, note that the 2nd argument to the callback is expected to be the user, not simply an authorized boolean. But, it can be any truthy value you desire, including the user name.

callback(null, config.credentials.clients[user].password == pass ? user : null);

After that, you should be able to retrieve it with:

var authUser = req.user;

Upvotes: 2

Related Questions