You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
68 lines
1.6 KiB
Go
68 lines
1.6 KiB
Go
package upload
|
|
|
|
import (
|
|
"bytes"
|
|
"crypto/hmac"
|
|
"crypto/sha1"
|
|
"joybuywork/internal/config"
|
|
"encoding/base64"
|
|
"encoding/json"
|
|
"fmt"
|
|
"github.com/rs/xid"
|
|
"hash"
|
|
"io"
|
|
"time"
|
|
)
|
|
|
|
type ConfigStruct struct {
|
|
Expiration string `json:"expiration"`
|
|
Conditions [][]string `json:"conditions"`
|
|
}
|
|
|
|
type PolicyToken struct {
|
|
Expire int64
|
|
Signature string
|
|
Policy string
|
|
Directory string
|
|
Key string
|
|
}
|
|
|
|
// GetPolicy 获取上传token
|
|
func GetPolicy(fileSuffix string) (policyToken PolicyToken) {
|
|
var (
|
|
exp = time.Now().Add(30 * time.Second)
|
|
expDate = exp.Format("2006-01-02T15:04:05Z")
|
|
secret = bytes.NewBufferString(config.Config.Upload.Secret)
|
|
dir = fmt.Sprintf("%s%s/", config.Config.Upload.Prefix, time.Now().Format("2006/01/02"))
|
|
filename = xid.New().String()
|
|
)
|
|
|
|
if fileSuffix != "" {
|
|
filename = fmt.Sprintf("%s.%s", filename, fileSuffix)
|
|
}
|
|
|
|
//create post policy json
|
|
var conf ConfigStruct
|
|
conf.Expiration = expDate
|
|
var condition []string
|
|
condition = append(condition, "starts-with")
|
|
condition = append(condition, "$key")
|
|
condition = append(condition, dir)
|
|
conf.Conditions = append(conf.Conditions, condition)
|
|
|
|
//calucate signature
|
|
result, _ := json.Marshal(conf)
|
|
debyte := base64.StdEncoding.EncodeToString(result)
|
|
h := hmac.New(func() hash.Hash { return sha1.New() }, secret.Bytes())
|
|
io.WriteString(h, debyte)
|
|
signedStr := base64.StdEncoding.EncodeToString(h.Sum(nil))
|
|
|
|
policyToken.Expire = int64(exp.Sub(time.Now()).Seconds())
|
|
policyToken.Signature = signedStr
|
|
policyToken.Directory = dir
|
|
policyToken.Policy = debyte
|
|
policyToken.Key = filename
|
|
|
|
return
|
|
}
|