feat: implement download token generation for secure file access

This commit is contained in:
2025-11-27 20:03:17 +08:00
parent e671083f09
commit 940393c150
3 changed files with 38 additions and 2 deletions

View File

@@ -225,7 +225,18 @@ func downloadFile(c fiber.Ctx) error {
return err
}
if strings.HasPrefix(s, "http") {
return c.Redirect().Status(fiber.StatusFound).To(s)
uri, err := url.Parse(s)
if err != nil {
return err
}
token, err := utils.GenerateDownloadToken(s)
if err != nil {
return err
}
q := uri.Query()
q.Set("token", token)
uri.RawQuery = q.Encode()
return c.Redirect().Status(fiber.StatusFound).To(uri.String())
}
data := map[string]string{
"path": s,

View File

@@ -3,9 +3,10 @@ package utils
import (
"crypto/rand"
"errors"
"github.com/golang-jwt/jwt/v5"
"os"
"time"
"github.com/golang-jwt/jwt/v5"
)
var (
@@ -93,3 +94,24 @@ func ParseTemporaryToken(token string) (string, error) {
}
return "", errors.New("invalid token")
}
func GenerateDownloadToken(fileKey string) (string, error) {
secretKeyStr := os.Getenv("DOWNLOAD_SECRET_KEY")
var secretKey []byte
if secretKeyStr == "" {
secretKey = key
} else {
secretKey = []byte(secretKeyStr)
}
t := jwt.NewWithClaims(jwt.SigningMethodHS256,
jwt.MapClaims{
"fileKey": fileKey,
"exp": time.Now().Add(1 * time.Hour).Unix(),
})
s, err := t.SignedString(secretKey)
if err != nil {
return "", err
}
return s, nil
}