forked from damian0501/awslab4
-
Notifications
You must be signed in to change notification settings - Fork 0
/
s3post.js
72 lines (55 loc) · 1.79 KB
/
s3post.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
var util = require("util");
var moment = require("moment");
var helpers = require("./helpers");
var Policy = function(policyData){
this.policy = policyData;
this.policy.expiration = moment().add(policyData.expiration).toJSON();
console.log("policyData " + util.inspect(policyData, false, null));
}
Policy.prototype.generateEncodedPolicyDocument = function(){
return helpers.encode(this.policy, 'base64');
}
Policy.prototype.getConditions = function(){
return this.policy.conditions;
}
Policy.prototype.generateSignature = function(secretAccessKey){
return helpers.hmac("sha1", secretAccessKey, this.generateEncodedPolicyDocument(), 'base64');
}
Policy.prototype.getConditionValueByKey = function(key){
var condition = [];
this.policy.conditions.forEach(function(elem) {
if(Object.keys(elem)[0] === key)
condition = elem[Object.keys(elem)[0]];
});
return condition;
}
var S3Form = function(awsCofig){
if(policy instanceof Policy)
this.policy = policy;
else{
console.log("policy instanceof Policy");
throw new Error("policy instanceof Policy");
}
}
S3Form.prototype.generateS3FormFields = function() {
var conditions =this.policy.getConditions();
var formFields = [];
conditions.forEach(function(elem){
if(Array.isArray(elem)){
if(elem[1] === "$key")
formFields.push(hiddenField("key", elem[2] + "${filename}"));
}else {
var key = Object.keys(elem)[0];
var value = elem[key];
if(key !== "bucket")
formFields.push(hiddenField(key, value));
}
});
return formFields;
}
S3Form.prototype.addHiddenField = hiddenField;
var hiddenField = function(fieldName, value) {
return {name: fieldName, value : value};
}
exports.Policy = Policy; // usage: policy = new Policy(policyData);
exports.S3Form = S3Form; // usage: s3Form = new S3Form(awsConfig, policy);