2024-01-06 13:10:24 +00:00
|
|
|
package security
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
"github.com/golang-jwt/jwt"
|
|
|
|
"os"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
type PresignToken struct {
|
|
|
|
Path string
|
|
|
|
}
|
|
|
|
|
2024-01-06 13:17:22 +00:00
|
|
|
type Type string
|
|
|
|
|
|
|
|
const (
|
|
|
|
TypeBasic Type = "basic"
|
|
|
|
TypeApi Type = "api"
|
|
|
|
TypeToken Type = "token"
|
|
|
|
)
|
|
|
|
|
2024-01-06 13:10:24 +00:00
|
|
|
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
|
|
|
|
}
|