-
Notifications
You must be signed in to change notification settings - Fork 0
/
decode.go
81 lines (73 loc) · 1.85 KB
/
decode.go
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
package internal
import (
"bytes"
"encoding/base64"
"encoding/json"
"strings"
"text/template"
"github.com/pkg/errors"
)
// DecodeOptions specifies options for decoding
type DecodeOptions struct {
JSON bool
Output string
}
// Decode jwt
func Decode(token []byte, opt DecodeOptions) (string, error) {
// Split and parse JWT
parts := bytes.Split(token, []byte("."))
if len(parts) != 3 {
return "", errors.New("Invalid token: requires 3 parts")
}
header := make(map[string]interface{})
payload := make(map[string]interface{})
obj := make(map[string]interface{})
err := decodePart(parts[0], &header)
if err != nil {
return "", errors.Wrap(err, "Invalid header")
}
err = decodePart(parts[1], &payload)
if err != nil {
return "", errors.Wrap(err, "Invalid payload")
}
obj["header"] = header
obj["payload"] = payload
// If json, prettyprint and return
if opt.JSON {
str, err := json.MarshalIndent(obj, "", " ")
return string(str) + "\n", err
}
// If output, parse template and execute
if len(opt.Output) > 0 {
t, err := template.New("").Parse(opt.Output)
if err != nil {
return "", errors.Wrap(err, "Invalid output")
}
var str bytes.Buffer
err = t.Execute(&str, obj)
if err != nil {
return "", errors.Wrap(err, "Invalid output")
}
return str.String(), nil
}
// Default output
var str strings.Builder
str.WriteString("HEADER:\n")
h, _ := json.MarshalIndent(header, "", " ")
str.Write(h)
str.WriteString("\n\n")
str.WriteString("PAYLOAD:\n")
p, _ := json.MarshalIndent(payload, "", " ")
str.Write(p)
str.WriteString("\n")
return str.String(), nil
}
func decodePart(encoded []byte, obj interface{}) error {
encoding := base64.RawURLEncoding
decoded := make([]byte, encoding.DecodedLen(len(encoded)))
_, err := encoding.Decode(decoded, encoded)
if err != nil {
return err
}
return json.Unmarshal(decoded, obj)
}