2023-03-13 10:44:58 +01:00
|
|
|
package thirdparty
|
2023-03-07 23:10:42 +01:00
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"time"
|
|
|
|
|
2024-02-26 18:20:40 +01:00
|
|
|
"forge.cadoles.com/Cadoles/emissary/internal/datastore"
|
2023-03-07 23:10:42 +01:00
|
|
|
"forge.cadoles.com/Cadoles/emissary/internal/jwk"
|
|
|
|
"github.com/lestrrat-go/jwx/v2/jwa"
|
|
|
|
"github.com/lestrrat-go/jwx/v2/jws"
|
|
|
|
"github.com/lestrrat-go/jwx/v2/jwt"
|
|
|
|
"github.com/pkg/errors"
|
|
|
|
)
|
|
|
|
|
2023-07-26 15:14:49 +02:00
|
|
|
func parseToken(ctx context.Context, keys jwk.Set, rawToken string, acceptableSkew time.Duration) (jwt.Token, error) {
|
2023-03-07 23:10:42 +01:00
|
|
|
token, err := jwt.Parse(
|
|
|
|
[]byte(rawToken),
|
|
|
|
jwt.WithKeySet(keys, jws.WithRequireKid(false)),
|
|
|
|
jwt.WithValidate(true),
|
2023-04-01 19:30:45 +02:00
|
|
|
jwt.WithAcceptableSkew(acceptableSkew),
|
2023-07-26 15:14:49 +02:00
|
|
|
jwt.WithContext(ctx),
|
2023-03-07 23:10:42 +01:00
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
return nil, errors.WithStack(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
return token, nil
|
|
|
|
}
|
|
|
|
|
2024-02-26 18:20:40 +01:00
|
|
|
const (
|
|
|
|
DefaultRoleKey string = "role"
|
|
|
|
DefaultTenantKey string = "tenant"
|
|
|
|
)
|
2023-07-26 15:14:49 +02:00
|
|
|
|
2024-02-26 18:20:40 +01:00
|
|
|
func GenerateToken(ctx context.Context, key jwk.Key, tenant datastore.TenantID, subject string, role Role) (string, error) {
|
2023-03-07 23:10:42 +01:00
|
|
|
token := jwt.New()
|
|
|
|
|
|
|
|
if err := token.Set(jwt.SubjectKey, subject); err != nil {
|
|
|
|
return "", errors.WithStack(err)
|
|
|
|
}
|
|
|
|
|
2023-07-26 15:14:49 +02:00
|
|
|
if err := token.Set(DefaultRoleKey, role); err != nil {
|
2023-03-07 23:10:42 +01:00
|
|
|
return "", errors.WithStack(err)
|
|
|
|
}
|
|
|
|
|
2024-02-26 18:20:40 +01:00
|
|
|
if err := token.Set(DefaultTenantKey, tenant); err != nil {
|
|
|
|
return "", errors.WithStack(err)
|
|
|
|
}
|
|
|
|
|
2023-03-29 20:49:44 +02:00
|
|
|
now := time.Now().UTC()
|
2023-03-07 23:10:42 +01:00
|
|
|
|
|
|
|
if err := token.Set(jwt.NotBeforeKey, now); err != nil {
|
|
|
|
return "", errors.WithStack(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := token.Set(jwt.IssuedAtKey, now); err != nil {
|
|
|
|
return "", errors.WithStack(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
rawToken, err := jwt.Sign(token, jwt.WithKey(jwa.RS256, key))
|
|
|
|
if err != nil {
|
|
|
|
return "", errors.WithStack(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
return string(rawToken), nil
|
|
|
|
}
|