Skip to content

Instantly share code, notes, and snippets.

@pulkitsinghal
Last active March 4, 2017 15:44
Show Gist options
  • Save pulkitsinghal/40c1a14c14d93d9cdcaf to your computer and use it in GitHub Desktop.
Save pulkitsinghal/40c1a14c14d93d9cdcaf to your computer and use it in GitHub Desktop.
How to create an AccessToken in LoopBack for a user
/** A quick github search for sample code:
* > https://github.com/search?utf8=%E2%9C%93&q=-1+AccessToken.create+path%3A%2Fcommon%2Fmodels&type=Code&ref=searchresults
* Yields two similar result:
* > https://github.com/patriciamolina/test/blob/90a8829728e4a404109e1eafa0a1075687042792/common/models/customer.js#L421
* > https://github.com/stormpath/loopback-stormpath/blob/e1cb4d98eacfe36ade2d58e1a48e6cfd590308ff/common/models/stormpath-user.js#L458
*/
module.exports = function(SellerModel) {
SellerModel.observe('after save', function(ctx, next) {
console.log('`after save` supports isNewInstance?', ctx.isNewInstance !== undefined);
if (ctx.isNewInstance !== undefined && ctx.isNewInstance) {
if (ctx.instance) { // don't want/expect to work with an array of SellerModels being created
console.log('Will create an additional AccessToken for user');
ctx.instance.accessTokens.create({
ttl:-1 // https://github.com/strongloop/loopback/pull/1797
}, function(err, obj){
if(err){
next(err);
} else {
next();
}
});
}
else {
next();
}
}
else {
next();
}
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment