s3browser-backend/internal/helper/helper.go
2021-10-14 19:00:11 +02:00

97 lines
1.9 KiB
Go

package helper
import (
"context"
"path/filepath"
"strings"
"time"
types "git.kapelle.org/niklas/s3browser/internal/types"
"github.com/golang-jwt/jwt"
"github.com/minio/minio-go/v7"
log "github.com/sirupsen/logrus"
)
func GetFilenameFromKey(id string) string {
return filepath.Base(id)
}
func DeleteMultiple(ctx context.Context, s3Client minio.Client, bucket string, keys []string) error {
log.Debug("Remove multiple objects")
objectsCh := make(chan minio.ObjectInfo, 1)
go func() {
defer close(objectsCh)
for _, id := range keys {
objectsCh <- minio.ObjectInfo{
Key: id,
}
}
}()
for err := range s3Client.RemoveObjects(ctx, bucket, 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 ObjInfoToFile(objInfo minio.ObjectInfo, bucket string) *types.File {
objID := types.ID{
Bucket: bucket,
Key: objInfo.Key,
}
objID.Normalize()
return &types.File{
ID: objID,
Name: GetFilenameFromKey(objID.Key),
Size: objInfo.Size,
ContentType: objInfo.ContentType,
ETag: objInfo.ETag,
LastModified: objInfo.LastModified,
}
}
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,
},
}
}