-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrecipient.go
More file actions
83 lines (65 loc) · 1.93 KB
/
recipient.go
File metadata and controls
83 lines (65 loc) · 1.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package jwt
import (
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"github.com/a-novel-kit/jwt/jwa"
)
type RecipientConfig struct {
// Sorted list of operations to perform on the token.
Plugins []RecipientPlugin
// Set a custom deserializer to decode the token's payload. Uses json.Unmarshal by default.
Deserializer func(raw []byte, dst any) error
}
type Recipient struct {
config RecipientConfig
}
func NewRecipient(config RecipientConfig) *Recipient {
if config.Plugins == nil {
config.Plugins = []RecipientPlugin{NewDefaultRecipientPlugin()}
}
return &Recipient{
config: config,
}
}
func (recipient *Recipient) Consume(ctx context.Context, rawToken string, dst any) error {
rawHeader, err := DecodeToken(rawToken, &HeaderDecoder{})
if err != nil {
return fmt.Errorf("(Recipient.Consume) decode token: %w", err)
}
decodedHeader, err := base64.RawURLEncoding.DecodeString(rawHeader)
if err != nil {
return fmt.Errorf("(Recipient.Consume) decode header: %w", err)
}
var header *jwa.JWH
err = json.Unmarshal(decodedHeader, &header)
if err != nil {
return fmt.Errorf("(Recipient.Consume) unmarshal header: %w", err)
}
if len(header.Crit) > 0 {
err = CheckCrit(decodedHeader, header.Crit)
if err != nil {
return fmt.Errorf("(Recipient.Consume) check crit: %w", err)
}
}
if recipient.config.Deserializer == nil {
recipient.config.Deserializer = json.Unmarshal
}
for _, plugin := range recipient.config.Plugins {
rawClaims, err := plugin.Transform(ctx, header, rawToken)
if err != nil {
if errors.Is(err, ErrMismatchRecipientPlugin) {
continue
}
return fmt.Errorf("(Recipient.Consume) transform token: %w", err)
}
err = recipient.config.Deserializer(rawClaims, dst)
if err != nil {
return fmt.Errorf("(Recipient.Consume) unmarshal claims: %w", err)
}
return nil
}
return fmt.Errorf("(Recipient.Consume) %w: no compatible plugin found", ErrMismatchRecipientPlugin)
}