get-object-url.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /*
  2. * Copyright (C) 2020 Tencent Cloud.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. 'use strict';
  17. const crypto = require('crypto');
  18. const { secretId, secretKey } = require('../config');
  19. const { bucket, region, expires } = require('./config');
  20. /**
  21. * 获取腾讯云COS文件的临时访问地址
  22. * @param {object} params - 参数包装对象
  23. * @param {string} params.key - 将要访问COS文件的名称
  24. * @return {string} COS文件的访问地址(包含临时签名)
  25. */
  26. function getObjectURL({ key }) {
  27. // 配置校验
  28. if (!secretId || !secretKey) {
  29. throw new Error('请云函数配置文件中配置secretId和secretKey');
  30. }
  31. if (!bucket || !region) {
  32. throw new Error('请在云函数COS模块中配置bucket和region');
  33. }
  34. if (isNaN(expires) || expires <= 0) {
  35. throw new Error('请在云函数COS模块中配置有效的expires');
  36. }
  37. // 生成签名信息
  38. const currentDate = new Date();
  39. const expirationDate = new Date(currentDate.getTime() + expires * 1000);
  40. const keyTime = `${Math.floor(currentDate.getTime() / 1000)};${Math.floor(expirationDate.getTime() / 1000)}`;
  41. const signKey = crypto.createHmac('sha1', secretKey).update(keyTime).digest('hex');
  42. const httpString = `get\n/${key}\n\n\n`;
  43. const httpStringHash = crypto.createHash('sha1').update(httpString).digest('hex');
  44. const stringToSign = `sha1\n${keyTime}\n${httpStringHash}\n`;
  45. const signature = crypto.createHmac('sha1', signKey).update(stringToSign).digest('hex');
  46. return (
  47. /* prettier-ignore */
  48. `https://${bucket}.cos.${region}.myqcloud.com/${key}`
  49. + `?q-sign-algorithm=sha1`
  50. + `&q-ak=${secretId}`
  51. + `&q-sign-time=${keyTime}`
  52. + `&q-key-time=${keyTime}`
  53. + `&q-header-list=`
  54. + `&q-url-param-list=`
  55. + `&q-signature=${signature}`
  56. );
  57. }
  58. module.exports = getObjectURL;