创建授权令牌

main
熊二 1 year ago
parent e9288ee253
commit b7f1f714ce
  1. 38
      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
}
Loading…
Cancel
Save