s3browser-backend/internal/helper/helper.go

68 lines
1.3 KiB
Go

package helper
import (
"context"
"path/filepath"
"strings"
"time"
"git.kapelle.org/niklas/s3browser/internal/s3"
types "git.kapelle.org/niklas/s3browser/internal/types"
"github.com/golang-jwt/jwt"
)
func GetFilenameFromKey(id string) string {
return filepath.Base(id)
}
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 s3.Object, bucket string) *types.File {
return &types.File{
ID: objInfo.ID,
Name: objInfo.ID.Name(),
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,
},
}
}