Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
module.exports = (event, context, callback) => {
const parsedEvent = JSON.parse(event);
const ossEvent = parsedEvent.events[0];
// Required by OSS sdk: OSS region is prefixed with "oss-", e.g. "oss-cn-shanghai"
const ossRegion = `oss-${ossEvent.region}`;
// Create oss client.
const client = new oss({
region: ossRegion,
bucket: ossEvent.oss.bucket.name,
// Credentials can be retrieved from context
accessKeyId: context.credentials.accessKeyId,
accessKeySecret: context.credentials.accessKeySecret,
stsToken: context.credentials.securityToken
});
const objKey = ossEvent.oss.object.key;
console.log('Getting object: ', objKey);
client.get(objKey).then(function(val) {
const newKey = objKey.replace('source/', 'processed/');
return client.put(newKey, val.content).then(function (val) {
console.log('Put object:', val);
callback(null, val);
}).catch(function (err) {
app.use(async (ctx, next) => {
lastReqTime = Date.now();
if (ctx.path === '/api/oss-config') {
ctx.body = {
accessKeyId,
accessKeySecret,
bucket,
region,
endpoint,
};
}
if (ctx.path === '/api/sts') {
const sts = new STS({
accessKeyId,
accessKeySecret,
});
// 60 mins
const expires = 60 * 60;
const sessionName = 'foo';
const stsToken = await sts.assumeRole(arn, undefined, expires, sessionName);
ctx.body = {
bucket,
region,
endpoint,
stsToken,
};
}
next();
});
'Example:',
' deploy:',
' type: aliyun',
' bucket: yourBucketName',
' region: yourOSSregion',
' accessKeyId: yourAccessKeyId',
' accessKeySecret: yourAccessKeySecret',
'',
'For more help, you can check the docs: ' + chalk.underline('http://hexo.io/docs/deployment.html') + ' and ' + chalk.underline('https://help.aliyun.com/document_detail/31867.html?spm=5176.doc31950.2.1.WMtDHS')
];
console.log(help.join('\n'));
log.error('config error');
return;
}
var client = new OSS({
region: args.region,
accessKeyId: args.accessKeyId,
accessKeySecret: args.accessKeySecret,
bucket: args.bucket
});
log.info('Uploading files to Aliyun...');
// get all files sync
traverseFiles(publicDir, function (file) {
uploadFileList.push({
uploadPath: getUploadPath(file, pathFn.basename(publicDir)),
file: file
});
});
customRequest = async (option) => {
this.setState({
loading: true
});
const res = await getSTS();
if (res && res.code === 0 && res.data) {
const client = new OSS({
...res.data,
expire: ''
});
// const fileName = `upload/${shortid.generate()}${getFileExt(option.file.name)}`;
const fileName = `${shortid.generate()}${getFileExt(option.file.name)}`;
const result = await client.put(fileName, option.file);
if (result.res && result.res.status === 200) {
option.onSuccess(result);
} else {
option.onError(result);
}
} else {
console.error('请实现自己的STS接口,详情可参考 https://help.aliyun.com/document_detail/32077.html?spm=a2c4g.11186623.6.788.qrBaau');
}
const aliOSSPutObject = ({config, file, buffer, onSuccess, onError, images, content}) => {
let client;
try {
client = new OSS(config);
} catch (error) {
message.error("OSS配置错误,请根据文档检查配置项");
return;
}
const OSSName = getOSSName(file.name);
client
.put(OSSName, buffer)
.then((response) => {
const names = file.name.split(".");
names.pop();
const filename = names.join(".");
const image = {
filename, // 名字不变并且去掉后缀
url: response.url,
// {
// accessKeyId: "keyId",
// accessKeySecret: "secret",
// bucket: "terminus-designer",
// region: "oss-cn-hangzhou"
// }
let { accessKeyId, accessKeySecret, bucket, region, targetProtocol, attachment, targetHost } = options
if (!targetHost) {
targetHost = `${bucket}.${region}.aliyuncs.com`
}
if (!(accessKeyId && accessKeySecret && bucket && region)) {
throw new Error("Missing option in options: [accessKeyId, accessKeySecret, bucket, region]")
}
const store = new oss(options)
return {
put: async (filename, file) => {
await util.fileResolve(file)
const opts = attachment === true ? {
headers: {
"Content-Disposition": `attachment;filename=${encodeURIComponent(file.filename)};filename*=UTF-8''${encodeURIComponent(file.filename)}`
}
} : undefined
return store.put(filename, file.path, opts)
},
get: (result) => {
Object.keys(result).map(filename => {
return result[filename] = `${targetProtocol ? `${targetProtocol}:` : ""}//${targetHost}/${result[filename]}`
})
return result
function kv(key, callback) {
const ossclient = new OSS({
region: 'oss-cn-beijing',
accessKeyId: accessKeyId,
accessKeySecret: accessKeySecret,
bucket: bucket
});
ossclient.get(key).then(function (res) {
const value = res.content; // plain text
if (isValidToken(value.toString())) {
callback(null, value);
} else {
renew((newValue) => { // plain text
// process expires_in value
const v = normalize(newValue); // JSON object
// refresh the OOS
ossclient.put(key, Buffer.from(stringify(v))); // buffer type
var OSS = require('ali-oss')
var localEnv = require('../config')
const request = require('request')
var client = new OSS.Wrapper({
region: localEnv.alioss.region,
accessKeyId: localEnv.alioss.AccessKeyId,
accessKeySecret: localEnv.alioss.AccessKeySecret
})
var aliyun = {
// 上传普通文件
upload: async (file, filename) => {
client.useBucket(localEnv.alioss.bucket)
return await client.put(filename, file)
},
// 上传网络图片
uploadUrl: async (url, filename) => {
var stream = require('stream')
var a = new stream.PassThrough()
var OSS = require('ali-oss')
var Helper = require('./helper')
var localEnv = Helper.readLocalEnv()
const fetchConfVal = (str) => {
let matchs = str.match(/^<(.+)>$/)
return matchs ? process.env[matchs[1]] : str
}
var client = new OSS.Wrapper({
region: localEnv.aliyun.region,
accessKeyId: fetchConfVal(localEnv.aliyun.accessKeyId),
accessKeySecret: fetchConfVal(localEnv.aliyun.accessKeySecret)
})
var aliyun = {
// 上传
upload: (file, removePrefix) => {
return new Promise(resolve => {
let fullname = Helper.uploadFileName(file, removePrefix)
client.useBucket(localEnv.aliyun.bucket)
client.put(fullname, file).then((data) => {
resolve()
})
})
}
it('getting container properties should fail with multiple buckets error', function () {
sandbox.restore();
sandbox.stub(AliStorage.prototype, 'useBucket').withArgs(settings.container).returns(listFilesStub);
sandbox.stub(AliStorage.prototype, 'listBuckets').withArgs({ prefix: settings.container }).callsFake(incorrectBucketStub2);
return client.getContainer()
.then(() => {
logger.error('The get container call should fails');
throw new Error('The get container call should fails');
})
.catch(err => {
expect(err.message).to.equal(`More than 1 Buckets with prefix ${settings.container} exists`);
});
});