signatureUrl.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. const urlutil = require('url');
  2. const utility = require('utility');
  3. const copy = require('copy-to');
  4. const signHelper = require('../../common/signUtils');
  5. const { isIP } = require('../utils/isIP');
  6. const { isFunction } = require('../../common/utils/isFunction');
  7. const { checkCredentials } = require('../utils/setSTSToken');
  8. const { formatObjKey } = require('../utils/formatObjKey');
  9. const proto = exports;
  10. proto.signatureUrl = function signatureUrl(name, options) {
  11. if (isIP(this.options.endpoint.hostname)) {
  12. throw new Error('can not get the object URL when endpoint is IP');
  13. }
  14. options = options || {};
  15. name = this._objectName(name);
  16. options.method = options.method || 'GET';
  17. const expires = utility.timestamp() + (options.expires || 1800);
  18. const params = {
  19. bucket: this.options.bucket,
  20. object: name
  21. };
  22. const resource = this._getResource(params);
  23. if (this.options.stsToken && isFunction(this.options.refreshSTSToken)) {
  24. const now = new Date();
  25. if (this.stsTokenFreshTime >= this.options.refreshSTSTokenInterval) {
  26. this.stsTokenFreshTime = now;
  27. this.options.refreshSTSToken().then(r => {
  28. const credentials = formatObjKey(r, 'firstLowerCase');
  29. if (credentials.securityToken) {
  30. credentials.stsToken = credentials.securityToken;
  31. }
  32. checkCredentials(credentials);
  33. Object.assign(this.options, credentials);
  34. });
  35. } else {
  36. this.stsTokenFreshTime = now;
  37. }
  38. }
  39. if (this.options.stsToken) {
  40. options['security-token'] = this.options.stsToken;
  41. }
  42. const signRes = signHelper._signatureForURL(this.options.accessKeySecret, options, resource, expires);
  43. const url = urlutil.parse(this._getReqUrl(params));
  44. url.query = {
  45. OSSAccessKeyId: this.options.accessKeyId,
  46. Expires: expires,
  47. Signature: signRes.Signature
  48. };
  49. copy(signRes.subResource).to(url.query);
  50. return url.format();
  51. };