From b7f1f714ce2a444e671978cbfa42dd0d78e98a9a Mon Sep 17 00:00:00 2001 From: hupeh Date: Tue, 19 Sep 2023 23:59:29 +0800 Subject: [PATCH] =?UTF-8?q?=E5=88=9B=E5=BB=BA=E6=8E=88=E6=9D=83=E4=BB=A4?= =?UTF-8?q?=E7=89=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- internal/util/ticket.go | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 internal/util/ticket.go diff --git a/internal/util/ticket.go b/internal/util/ticket.go new file mode 100644 index 0000000..ff178d3 --- /dev/null +++ b/internal/util/ticket.go @@ -0,0 +1,38 @@ +package util + +import ( + "github.com/golang-jwt/jwt/v5" + "github.com/rs/xid" + "sorbet/pkg/env" + "sorbet/pkg/ticket" + "time" +) + +func CreateTicket(claims *ticket.Claims) (string, error) { + if claims.ID == "" { + claims.ID = xid.New().String() + } + if claims.Issuer == "" { + claims.Issuer = env.String("TICKET_ISSUER") + } + if claims.Subject == "" { + claims.Issuer = env.String("TICKET_SUBJECT") + } + if claims.Audience == nil { + claims.Audience = env.List("TICKET_AUDIENCE") + } + if claims.ExpiresAt == nil { + ttl := env.Duration("TICKET_TTL", time.Hour) + claims.ExpiresAt = jwt.NewNumericDate(time.Now().Add(ttl)) + } + source := []byte(env.String("TICKET_PRIVATE_KEY")) + privateKey, err := jwt.ParseRSAPrivateKeyFromPEM(source) + if err != nil { + return "", err + } + signedString, err := ticket.Create(claims, privateKey) + if err != nil { + return "", err + } + return signedString, nil +}