s3browser-backend/internal/helper/helper.go

120 lines
2.6 KiB
Go

package helper
import (
"context"
"fmt"
"path/filepath"
"strings"
"time"
"github.com/golang-jwt/jwt"
"github.com/graph-gophers/dataloader"
"github.com/minio/minio-go/v7"
log "github.com/sirupsen/logrus"
types "git.kapelle.org/niklas/s3browser/internal/types"
)
func InvalidateCache(ctx context.Context, id types.ID) error {
loader, ok := ctx.Value("loader").(map[string]*dataloader.Loader)
if !ok {
return fmt.Errorf("Failed to get loader from context")
}
log.Debug("Invalidate cache for id: ", id)
parent := id.Parent()
loader["getFile"].Clear(ctx, id)
loader["getFiles"].Clear(ctx, parent)
loader["listObjects"].Clear(ctx, parent)
loader["listObjectsRecursive"].Clear(ctx, parent)
return nil
}
func GetFilenameFromKey(id string) string {
return filepath.Base(id)
}
func InvalidateCacheForDir(ctx context.Context, path types.ID) error {
loader, ok := ctx.Value("loader").(map[string]*dataloader.Loader)
if !ok {
return fmt.Errorf("Failed to get loader from context")
}
log.Debug("Invalidate cache for dir: ", path)
parent := GetParentDir(path)
log.Debug("Cache clear dir: ", path, " parent: ", parent)
loader["getFile"].Clear(ctx, path)
loader["listObjects"].Clear(ctx, path)
loader["listObjectsRecursive"].Clear(ctx, path)
loader["getFiles"].Clear(ctx, path)
loader["getDirs"].Clear(ctx, parent)
loader["listObjects"].Clear(ctx, parent)
loader["listObjectsRecursive"].Clear(ctx, parent)
return nil
}
func DeleteMultiple(ctx context.Context, s3Client minio.Client, ids []minio.ObjectInfo) error {
log.Debug("Delte multiple")
objectsCh := make(chan minio.ObjectInfo, 1)
go func() {
defer close(objectsCh)
for _, id := range ids {
objectsCh <- id
}
}()
for err := range s3Client.RemoveObjects(ctx, "dev", objectsCh, minio.RemoveObjectsOptions{}) {
log.Error("Failed to delete object ", err.ObjectName, " because: ", err.Err.Error())
// TODO: error handel
}
return nil
}
func GetParentDir(id types.ID) types.ID {
dirs := strings.Split(id.Key, "/")
cut := 1
if strings.HasSuffix(id.Key, "/") {
cut = 2
}
parentKey := strings.Join(dirs[:len(dirs)-cut], "/") + "/"
parent := types.ID{
Bucket: id.Bucket,
Key: parentKey,
}
parent.Normalize()
return parent
}
func IsAuthenticated(ctx context.Context) bool {
token, ok := ctx.Value("jwt").(*jwt.Token)
return (ok && token.Valid)
}
func CreateJWT(claims *types.JWTClaims) *jwt.Token {
claims.ExpiresAt = time.Now().Add(time.Hour * 24).Unix()
return jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
}
func CreateClaims(username string) *types.JWTClaims {
return &types.JWTClaims{
StandardClaims: jwt.StandardClaims{
Subject: username,
},
}
}