file_system_credentials.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. var AWS = require('../core');
  2. /**
  3. * Represents credentials from a JSON file on disk.
  4. * If the credentials expire, the SDK can {refresh} the credentials
  5. * from the file.
  6. *
  7. * The format of the file should be similar to the options passed to
  8. * {AWS.Config}:
  9. *
  10. * ```javascript
  11. * {accessKeyId: 'akid', secretAccessKey: 'secret', sessionToken: 'optional'}
  12. * ```
  13. *
  14. * @example Loading credentials from disk
  15. * var creds = new AWS.FileSystemCredentials('./configuration.json');
  16. * creds.accessKeyId == 'AKID'
  17. *
  18. * @!attribute filename
  19. * @readonly
  20. * @return [String] the path to the JSON file on disk containing the
  21. * credentials.
  22. * @!macro nobrowser
  23. */
  24. AWS.FileSystemCredentials = AWS.util.inherit(AWS.Credentials, {
  25. /**
  26. * @overload AWS.FileSystemCredentials(filename)
  27. * Creates a new FileSystemCredentials object from a filename
  28. *
  29. * @param filename [String] the path on disk to the JSON file to load.
  30. */
  31. constructor: function FileSystemCredentials(filename) {
  32. AWS.Credentials.call(this);
  33. this.filename = filename;
  34. this.get(function() {});
  35. },
  36. /**
  37. * Loads the credentials from the {filename} on disk.
  38. *
  39. * @callback callback function(err)
  40. * Called after the JSON file on disk is read and parsed. When this callback
  41. * is called with no error, it means that the credentials information
  42. * has been loaded into the object (as the `accessKeyId`, `secretAccessKey`,
  43. * and `sessionToken` properties).
  44. * @param err [Error] if an error occurred, this value will be filled
  45. * @see get
  46. */
  47. refresh: function refresh(callback) {
  48. if (!callback) callback = AWS.util.fn.callback;
  49. try {
  50. var creds = JSON.parse(AWS.util.readFileSync(this.filename));
  51. AWS.Credentials.call(this, creds);
  52. if (!this.accessKeyId || !this.secretAccessKey) {
  53. throw AWS.util.error(
  54. new Error('Credentials not set in ' + this.filename),
  55. { code: 'FileSystemCredentialsProviderFailure' }
  56. );
  57. }
  58. this.expired = false;
  59. callback();
  60. } catch (err) {
  61. callback(err);
  62. }
  63. }
  64. });