2015-01-07 3 views
2

Stormpath documentation ничего не говорит об изменении атрибутов пользователя в PostRegistrationHandler, и мне нужно это сделать.Express.js 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 линию НЕ распечатать CustomData с атрибутом mongo_id. Когда я попытаюсь получить к нему доступ позже с req.user.customData ['mongo_id'], его там нет. Учетная запись и req.user должны быть разными. Как я могу сохранить пользователя?

+0

Вопрос: Вы используете опцию «expandCustomData» для библиотеки? – robertjd

+0

Я не использую expandCustomData – Mike

+0

Можете ли вы попробовать добавить эту опцию? Я подозреваю, что это может потребоваться для работы с пользовательскими данными в обработчике post registration – robertjd

ответ

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

Надежда, что помогает!

0

Решение, предоставляемое rdegges, не совсем корректно.

Вызов 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); 
    }); 
}, 
Смежные вопросы