Search code examples
node.jsstormpathexpress-stormpath

Stormpath multi-tenant express


i am trying to learn how to make a multi-tenant app with stormpath and node with express. This is the official document on that topic. As for now i am using express-stormpath lib to make my login and stuff. But i can not find how i do the multi-tenant.

UPDATE I got it to work with passport stormpath strategy. I do not know if that is the right way but it works... The problem now is how do i change accountStore dynamic in the express version? It feels like a public declared variable is not so good?

var href = {
  href: null
}

function hrefUrl(req, res, next){
  var host = req.headers.host;
  var account = host.split(".")[0];

  spClient.getDirectories(function (err, directories) {
    directories.each(function (dir, cb){
      if(account.toLowerCase() == dir.name.toLowerCase()){
        href.href = dir.href
      }
      cb();
    }, function (err){
      if(href.href == null){
        return res.redirect(301, 'http://dashboard.local.dev/selectCompany');
      }
      next();
    });
  });
}

// Authenticate a user.
router.post('/login', hrefUrl, passport.authenticate('stormpath',
    {
      successRedirect: '/dashboard',
      failureRedirect: '/login',
      failureFlash: 'Invalid email or password.',
      accountStore: href
    }
  )
);

Solution

  • Express-stormpath has provided APIs for you to access account information in your application. These accounts belong to directories. From the official document, you have two solutions to support multi-tenant. One is to create group per tenant, and another is to create directory per tenant.

    For either solution you choose, you would have to use the APIs provided by express-stormpath to access these information associated with an account.

    For example if you have created different directories for each tenant, you may need to add your business logics regarding to the multi-tenant in the postLoginHandler.

    app.use(stormpath.init(app, {
        postLoginHandler: function (account, req, res, next) {
            account.getDirectory(function(err, directory) {
                console.log(directory)
                // if directory is tenant-1
                // if directory is tenant-2
            })
        }
    })