-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
80 lines (75 loc) · 2.29 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
var AWS = require('aws-sdk');
AWS.config.update({region: 'us-east-1'});
var s3 = new AWS.S3({apiVersion: '2006-03-01'});
exports.handler = (event, context, callback) => {
var bucket = event.Records[0].s3.bucket.name;
var key = event.Records[0].s3.object.key.replace(/\+/g, " ");
console.log('Checking object ' + key + ' in bucket ' + bucket);
var params = {
Bucket: bucket,
Key: key
};
s3.getObjectAcl(params, function(err, data) {
if (err) {
console.log(err, err.stack);
} else {
console.log(data);
processObjectAcl(bucket, key, data.Owner.DisplayName, callback);
}
});
};
/**
* Processes getObjectAcl request on newly added object. Checks owner
* against bucket owner.
* @param {string} bucket Name of S3 bucket containing object to change.
* @param {string} key Key of S3 object whose owner must be checked.
* @param {string} owner Owner display name of S3 object that was created.
* @param {function} callback Callback function provided by AWS Lambda.
*/
function processObjectAcl(bucket, key, owner, callback) {
var params = {
Bucket: bucket
};
s3.getBucketAcl(params, function(err, data) {
if (err) {
console.log(err, err.stack);
callback(err);
} else {
console.log(data);
if (owner != data.Owner.DisplayName) {
console.log('Switch needed');
changeOwner(bucket, key, callback);
} else {
console.log('No switch needed');
callback(null, 'Success');
}
}
});
}
/**
* Changes the owner of the given key within the given bucket by
* copying/overwriting the existing object under the account of
* this function.
* @param {string} bucket Name of S3 bucket containing object to change.
* @param {string} key Key of S3 object whose owner will change.
* @param {function} callback Callback function provided by AWS Lambda.
*/
function changeOwner(bucket, key, callback) {
var params = {
Bucket: bucket,
CopySource: bucket + '/' + key,
Key: key,
ACL: 'private',
StorageClass: 'STANDARD'
};
s3.copyObject(params, function(err, data) {
if (err) {
console.log(err, err.stack);
callback(err);
} else {
console.log(data);
callback(null, 'Success');
}
});
callback(null, 'Success');
}