2

Stormpath文档 没有说明在 PostRegistrationHandler 中修改用户属性,我需要能够做到这一点。

创建用户后,我想给它一个随机字符串作为属性。这个随机字符串将成为我单独的 Mongo 数据库的键。在我的 app.js 中,我有:

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

}));

我不知道我的 console.log 行如何打印出带有 mongo_id 属性的 customData。当我稍后尝试使用 req.user.customData['mongo_id'] 访问它时,它不存在。Account 和 req.user 必须不同。如何保存用户?

4

2 回答 2

2

我是上面提到的库的作者,所以我认为这会有所帮助。

我已修改您的代码以使其正常工作 =)

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
}));

希望有帮助!

于 2015-01-09T19:04:30.823 回答
0

rdegges 提供的解决方案并不完全正确。

只能在 customData 完成保存后调用 to next(),而不是立即调用,因此它必须是data.save().

此外,显然postRegistrationHandler参数已更改为account, req, res, next.

这是当前有效的解决方案:

postRegistrationHandler: function(account, req, res, next) {
    account.getCustomData(function(err, data) {
        if (err)
            return next(err);

        data.mongo_id = '54aabc1c79f3e058eedcd2a7';
        data.save(next);
    });
},
于 2015-07-16T08:40:36.277 回答