Search code examples
stormpath

Express.js Stormpath PostRegistrationHandler


The Stormpath documentation says nothing about modifying user attributes in the PostRegistrationHandler, and I need to be able to do this.

After creating a user, I want to give it a random string as a property. This random string will be a key into my separate Mongo Database. In my app.js, I have:

app.use(stormpath.init(app, {

postRegistrationHandler: function(account, res, next) {

// theoretically, this will give a user object a new property, 'mongo_id'
// which will be used to retrieve user info out of MONGOOOO
account.customData["mongo_id"] = "54aabc1c79f3e058eedcd2a7"; // <- this is the thing I'm trying to add

console.log("RESPNSE:\n"+res);  

account.save(); // I know I'm using 'account', instead of user, but the documentation uses account. I don't know how to do this any other way
next();
console.log('User:\n', account, '\njust registered!');
},

apiKeyId: '~/.stormpath.apiKey.properties',
//apiKeySecret: 'xxx',
application: ~removed~,
secretKey: ~removed~,
redirectUrl: '/dashboard',
enableAutoLogin: true

}));

I don't know how to my console.log line DOES print out customData with the mongo_id attribute. When I try to access it later with req.user.customData['mongo_id'], it isn't there. Account and req.user must be different. How can I save the user?


Solution

  • I'm the author of the library mentioned above, so I think this will help a bit.

    I've modified your code to work properly =)

    app.use(stormpath.init(app, {
      postRegistrationHandler: function(account, res, next) {
        // The postRegistrationHandler is a special function that returns the account
        // object AS-IS. This means that you need to first make the account.customData stuff
        // available using account.getCustomData as described here:
        // http://docs.stormpath.com/nodejs/api/account#getCustomData
        account.getCustomData(function(err, data) {
          if (err) {
            return next(err);
          } else {
            data.mongo_id = '54aabc1c79f3e058eedcd2a7';
            data.save();
            next();
          }
        });
      },
      apiKeyId: 'xxx',
      apiKeySecret: 'xxx',
      application: ~removed~,
      secretKey: ~removed~,
      redirectUrl: '/dashboard',
      enableAutoLogin: true,
      expandCustomData: true,  // this option makes req.user.customData available by default
                               // everywhere EXCEPT the postRegistrationHandler
    }));
    

    Hope that helps!