56 lines
1.5 KiB
Go
56 lines
1.5 KiB
Go
package encryption
|
|
|
|
import (
|
|
"fmt"
|
|
"os"
|
|
"time"
|
|
|
|
"github.com/golang-jwt/jwt/v5"
|
|
"jonasled.dev/jonasled/hostware-vnc-proxy/log"
|
|
"jonasled.dev/jonasled/hostware-vnc-proxy/types"
|
|
)
|
|
|
|
func DecodePayload(payload string) (*types.PayloadClaim, error) {
|
|
token, err := jwt.ParseWithClaims(payload, &types.PayloadClaim{}, func(token *jwt.Token) (interface{}, error) {
|
|
return []byte(os.Getenv("JWT_SIGN_KEY")), nil
|
|
})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if token.Valid {
|
|
claims, _ := token.Claims.(*types.PayloadClaim)
|
|
return claims, nil
|
|
} else {
|
|
log.Log.Error("Failed decoding JWT, invalid token provided")
|
|
return nil, fmt.Errorf("invalid token")
|
|
}
|
|
|
|
}
|
|
|
|
func EncodePayload(payload *types.PayloadClaim) (string, error) {
|
|
// Retrieve the signing key
|
|
signingKey := os.Getenv("JWT_SIGN_KEY")
|
|
if signingKey == "" {
|
|
log.Log.Error("JWT_SIGN_KEY environment variable not set")
|
|
return "", fmt.Errorf("signing key not available")
|
|
}
|
|
|
|
// Set standard claims (e.g., issued at, expiration)
|
|
now := time.Now()
|
|
payload.RegisteredClaims.IssuedAt = jwt.NewNumericDate(now)
|
|
if payload.RegisteredClaims.ExpiresAt == nil {
|
|
payload.RegisteredClaims.ExpiresAt = jwt.NewNumericDate(now.Add(24 * time.Hour)) // Default to 24 hours expiration
|
|
}
|
|
|
|
// Create the token
|
|
token := jwt.NewWithClaims(jwt.SigningMethodHS256, payload)
|
|
|
|
// Sign the token
|
|
tokenString, err := token.SignedString([]byte(signingKey))
|
|
if err != nil {
|
|
log.Log.Error("Failed signing the JWT: ", err.Error())
|
|
return "", err
|
|
}
|
|
|
|
return tokenString, nil
|
|
}
|