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

@@ -30,3 +30,6 @@ BACKUP_SCHEDULE=0 2 * * *
# Retention policy (days) # Retention policy (days)
BACKUP_RETENTION_DAYS=30 BACKUP_RETENTION_DAYS=30
# Download Configuration
DOWNLOAD_SECRET_KEY=your_download_secret_key_here

View File

@@ -225,7 +225,18 @@ func downloadFile(c fiber.Ctx) error {
return err return err
} }
if strings.HasPrefix(s, "http") { 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{ data := map[string]string{
"path": s, "path": s,

View File

@@ -3,9 +3,10 @@ package utils
import ( import (
"crypto/rand" "crypto/rand"
"errors" "errors"
"github.com/golang-jwt/jwt/v5"
"os" "os"
"time" "time"
"github.com/golang-jwt/jwt/v5"
) )
var ( var (
@@ -93,3 +94,24 @@ func ParseTemporaryToken(token string) (string, error) {
} }
return "", errors.New("invalid token") 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
}