s3browser-backend/internal/helper/helper.go

97 lines
1.9 KiB
Go
Raw Normal View History

2021-09-24 13:39:23 +00:00
package helper
2021-08-14 12:13:49 +00:00
import (
"context"
"path/filepath"
2021-09-03 13:03:32 +00:00
"strings"
2021-09-23 23:27:19 +00:00
"time"
2021-08-14 12:13:49 +00:00
2021-10-14 17:00:11 +00:00
types "git.kapelle.org/niklas/s3browser/internal/types"
2021-09-14 14:51:01 +00:00
"github.com/golang-jwt/jwt"
2021-08-20 19:38:22 +00:00
"github.com/minio/minio-go/v7"
2021-08-16 20:40:10 +00:00
log "github.com/sirupsen/logrus"
2021-08-14 12:13:49 +00:00
)
func GetFilenameFromKey(id string) string {
2021-08-15 23:40:01 +00:00
return filepath.Base(id)
}
2021-08-16 20:16:42 +00:00
2021-10-14 17:00:11 +00:00
func DeleteMultiple(ctx context.Context, s3Client minio.Client, bucket string, keys []string) error {
log.Debug("Remove multiple objects")
2021-08-20 19:38:22 +00:00
objectsCh := make(chan minio.ObjectInfo, 1)
go func() {
defer close(objectsCh)
2021-10-14 17:00:11 +00:00
for _, id := range keys {
objectsCh <- minio.ObjectInfo{
Key: id,
}
2021-08-20 19:38:22 +00:00
}
}()
2021-10-14 17:00:11 +00:00
for err := range s3Client.RemoveObjects(ctx, bucket, objectsCh, minio.RemoveObjectsOptions{}) {
2021-08-20 19:38:22 +00:00
log.Error("Failed to delete object ", err.ObjectName, " because: ", err.Err.Error())
// TODO: error handel
}
return nil
}
2021-09-03 13:03:32 +00:00
func GetParentDir(id types.ID) types.ID {
dirs := strings.Split(id.Key, "/")
2021-09-03 13:03:32 +00:00
cut := 1
if strings.HasSuffix(id.Key, "/") {
2021-09-03 13:03:32 +00:00
cut = 2
}
parentKey := strings.Join(dirs[:len(dirs)-cut], "/") + "/"
parent := types.ID{
Bucket: id.Bucket,
Key: parentKey,
}
parent.Normalize()
2021-09-03 13:03:32 +00:00
return parent
2021-09-03 13:03:32 +00:00
}
2021-09-14 14:51:01 +00:00
2021-10-14 17:00:11 +00:00
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,
}
}
2021-09-24 13:49:51 +00:00
func IsAuthenticated(ctx context.Context) bool {
2021-09-14 14:51:01 +00:00
token, ok := ctx.Value("jwt").(*jwt.Token)
2021-09-24 13:49:51 +00:00
return (ok && token.Valid)
2021-09-14 14:51:01 +00:00
}
2021-09-23 23:27:19 +00:00
2021-09-24 13:39:23 +00:00
func CreateJWT(claims *types.JWTClaims) *jwt.Token {
2021-09-23 23:27:19 +00:00
claims.ExpiresAt = time.Now().Add(time.Hour * 24).Unix()
return jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
}
2021-09-24 13:39:23 +00:00
func CreateClaims(username string) *types.JWTClaims {
return &types.JWTClaims{
2021-09-23 23:27:19 +00:00
StandardClaims: jwt.StandardClaims{
Subject: username,
},
}
}