resource_manager/security/generator.go

53 lines
1.1 KiB
Go

package security
import (
"errors"
"github.com/golang-jwt/jwt"
"os"
"time"
)
type PresignToken struct {
Path string
}
func CreateToken(tokenInfo PresignToken, duration time.Duration) (string, error) {
// jwt token
atClaims := jwt.MapClaims{}
atClaims["authorized"] = true
// user info
atClaims["path"] = tokenInfo.Path
// expiration
atClaims["exp"] = time.Now().Add(duration).Unix()
at := jwt.NewWithClaims(jwt.SigningMethodHS256, atClaims)
secret := getSecret()
return at.SignedString([]byte(secret))
}
func ParseToken(token string) (PresignToken, error) {
secret := getSecret()
parsedToken, err := jwt.Parse(token, func(t *jwt.Token) (interface{}, error) {
return []byte(secret), nil
})
if err != nil {
return PresignToken{}, err
}
claims, ok := parsedToken.Claims.(jwt.MapClaims)
if ok {
return PresignToken{
Path: claims["path"].(string),
}, nil
} else {
return PresignToken{}, errors.New("failed parsing token")
}
}
func getSecret() string {
secret, exists := os.LookupEnv("JWT_SECRET")
if !exists {
panic("env variable JWT_SECRET not set")
}
return secret
}