github.com/seeker-insurance/kit@v0.0.13/s3/uploader/uploader.go (about)

     1  package uploader
     2  
     3  import (
     4  	"crypto/hmac"
     5  	"crypto/sha1"
     6  	"encoding/base64"
     7  	"encoding/json"
     8  	"fmt"
     9  	"time"
    10  
    11  	"github.com/google/uuid"
    12  	"github.com/spf13/viper"
    13  )
    14  
    15  // Config s3 uploader config data type
    16  type Config struct {
    17  	ID             string `jsonapi:"primary,uploader_config"`
    18  	Key            string `jsonapi:"attr,key"`
    19  	ACL            string `jsonapi:"attr,acl"`
    20  	AwsAccessKeyID string `jsonapi:"attr,awsAccessKeyId"`
    21  	S3Policy       string `jsonapi:"attr,s3Policy"`
    22  	S3Signature    string `jsonapi:"attr,s3Signature"`
    23  	S3Bucket       string `jsonapi:"attr,s3Bucket"`
    24  	// ContentType    string `jsonapi:"attr,contentType"`
    25  }
    26  
    27  // Policy data type
    28  type Policy struct {
    29  	Expiration string        `json:"expiration"`
    30  	Conditions []interface{} `json:"conditions"`
    31  }
    32  
    33  // ACL ...
    34  func ACL() string {
    35  	return "public-read"
    36  }
    37  
    38  // PolicyString ...
    39  func PolicyString(key string) string {
    40  	policyData := GetPolicy(key)
    41  	policyDataJSON, _ := json.Marshal(policyData)
    42  	return base64.StdEncoding.EncodeToString(policyDataJSON)
    43  }
    44  
    45  // Signature policy signature
    46  func Signature(policy string) string {
    47  	sigKey := []byte(viper.GetString("aws_secret"))
    48  
    49  	sig := hmac.New(sha1.New, sigKey)
    50  	sig.Write([]byte(policy))
    51  	return base64.StdEncoding.EncodeToString(sig.Sum(nil))
    52  }
    53  
    54  // Key s3 file key
    55  func Key(pref string) string {
    56  	key := uuid.New().String()
    57  	return fmt.Sprintf("%s/%s/", pref, key)
    58  }
    59  
    60  // GetPolicy generate policy for the file
    61  func GetPolicy(key string) Policy {
    62  	data := Policy{
    63  		time.Now().UTC().Add(time.Hour * 10).Format(time.RFC3339),
    64  		[]interface{}{
    65  			[]string{"starts-with", "$key", key},
    66  			map[string]string{"bucket": viper.GetString("aws_bucket_name")},
    67  			map[string]string{"acl": ACL()},
    68  			map[string]string{"success_action_status": "201"},
    69  			[]interface{}{"content-length-range", 1, 1073741824}, // TODO: use max size based on the type of the resource
    70  		},
    71  	}
    72  	// TODO: validate content type based on the resource
    73  	// conditions << [ 'starts-with', '$Content-Type', contentType]
    74  
    75  	return data
    76  }