Skip to content

Instantly share code, notes, and snippets.

@passatgt
Created August 8, 2016 19:06
Show Gist options
  • Save passatgt/6281a63bc2ad2dcdf9b7150d9a8ec491 to your computer and use it in GitHub Desktop.
Save passatgt/6281a63bc2ad2dcdf9b7150d9a8ec491 to your computer and use it in GitHub Desktop.
Routes to generate, list and delete api keys using Node.js Stormpath Express
// Create api key
module.exports.createApiKey = function(req, res) {
req.user.createApiKey(function(err, apiKey){
if(err) return helpers.handleError(err,res);
return res.status(201).send({status: 'success', code: 'api_key_created', message: 'Api key created.', data: apiKey});
});
}
// Get api keys
module.exports.getApiKey = function(req, res) {
req.user.getApiKeys(function(err, apiKeys){
if(err) return helpers.handleError(err,res);
if(apiKeys.size>0) {
return res.status(200).send({status: 'success', code: 'api_keys_found', message: 'Api key found.', data: apiKeys});
} else {
return res.status(404).send({status: 'fail', code: 'no_api_keys', message: "You don't have api keys"});
}
});
}
// Delete api keys
module.exports.deleteApiKey = function(req, res) {
req.app.get('stormpathApplication').getApiKey(req.params.id, function(err, apiKey){
if(err) return helpers.handleError(err,res);
if(apiKey) {
apiKey.delete(function(){
return res.status(200).send({status: 'success', code: 'api_key_deleted', message: 'API key deleted.'});
});
} else {
return res.status(404).send({status: 'fail', code: 'not_found', message: "Selected API key not found."});
}
});
}
// Generate token for API keys authentication
module.exports.generateToken = function(req,res) {
req.app.get('stormpathApplication').authenticateApiRequest({
request: req
}, function(err,authResult){
if(err) return helpers.handleError(err,res);
return res.status(200).send(authResult.tokenResponse);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment