|
|
const moment = require('moment')
|
|
|
const crypto = require('crypto')
|
|
|
const qs = require('querystring')
|
|
|
const url = require('url')
|
|
|
const _ = require('lodash')
|
|
|
const cdn_config = require('../config/cdn_config')
|
|
|
|
|
|
const config = cdn_config.qcloud;
|
|
|
|
|
|
module.exports = {
|
|
|
SHA1(str) {
|
|
|
return crypto.createHash('sha1').update(str).digest('hex')
|
|
|
},
|
|
|
HMACSHA1(str, secret) {
|
|
|
return crypto.createHmac('sha1', secret).update(str).digest('hex')
|
|
|
},
|
|
|
sort(obj){
|
|
|
const newData = {};
|
|
|
|
|
|
Object.keys(obj).sort().forEach(key => {
|
|
|
newData[key] = String(obj[key]);
|
|
|
});
|
|
|
|
|
|
return newData
|
|
|
},
|
|
|
sign(data) {
|
|
|
// https://cloud.tencent.com/document/product/614/12445
|
|
|
data.headers = data.headers || {}
|
|
|
data.headers.host = url.parse(data.baseUrl).host
|
|
|
|
|
|
data.headers = this.sort(data.headers) || {}
|
|
|
data.qs = this.sort(data.qs) || {}
|
|
|
|
|
|
const formatedParameters = qs.stringify(data.qs)
|
|
|
const formatedHeaders = qs.stringify(data.headers)
|
|
|
|
|
|
const httpRequestInfo = [data.method, data.uri, formatedParameters, formatedHeaders].join('\n') + '\n'
|
|
|
|
|
|
const qSignTime = `${moment().unix()};${moment(Date.now() + 60 * 1000).unix()}`
|
|
|
const stringToSign = ['sha1', qSignTime, this.SHA1(httpRequestInfo)].join('\n') + '\n'
|
|
|
|
|
|
const qKeyTime = qSignTime
|
|
|
const signKey = this.HMACSHA1(qKeyTime, config.SecretKey)
|
|
|
|
|
|
const signature = this.HMACSHA1(stringToSign, signKey)
|
|
|
|
|
|
const authorization = `q-sign-algorithm=sha1&q-ak=${config.SecretId}&q-sign-time=${qSignTime}&q-key-time=${qKeyTime}&q-header-list=${Object.keys(data.headers).join(';')}&q-url-param-list=${Object.keys(data.qs).join(';')}&q-signature=${signature}`
|
|
|
|
|
|
data.headers.Authorization = authorization
|
|
|
|
|
|
return data
|
|
|
}
|
|
|
} |
...
|
...
|
|