-
Notifications
You must be signed in to change notification settings - Fork 3
/
jwt.go
140 lines (94 loc) · 2.15 KB
/
jwt.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
package jwt
import (
"errors"
"time"
"github.com/golang-jwt/jwt/v4"
"github.com/zolamk/trust/config"
"github.com/zolamk/trust/model"
)
type JWT struct {
jwt.RegisteredClaims
Name *string `json:"name,omitempty"`
Email *string `json:"email,omitempty"`
Phone *string `json:"phone,omitempty"`
Metadata *interface{} `json:"metadata,omitempty"`
Provider string `json:"provider"`
config *config.Config
}
func New(provider string, user *model.User, metadata *interface{}, config *config.Config) *JWT {
now := time.Now()
return &JWT{
jwt.RegisteredClaims{
Audience: jwt.ClaimStrings{config.JWT.Aud},
ExpiresAt: jwt.NewNumericDate(now.Add(time.Minute * config.JWT.Exp)),
Issuer: config.JWT.Iss,
Subject: user.ID,
},
user.Name,
user.Email,
user.Phone,
metadata,
provider,
config,
}
}
func Decode(signed_string string, config *config.Config) (*JWT, error) {
claims := &JWT{
config: config,
}
token, err := jwt.ParseWithClaims(signed_string, claims, func(t *jwt.Token) (interface{}, error) {
return config.JWT.GetDecodingKey(), nil
})
if err != nil {
return nil, err
}
if !token.Valid {
return nil, errors.New("invalid jwt")
}
claims, ok := token.Claims.(*JWT)
if !ok {
return nil, errors.New("couldn't case jwt claims")
}
return claims, nil
}
func (j *JWT) Sign() (string, error) {
alg := jwt.GetSigningMethod(j.config.JWT.Alg)
token := jwt.NewWithClaims(alg, j)
return token.SignedString(j.config.JWT.GetSigningKey())
}
func (j *JWT) roles() []interface{} {
roles := []interface{}{}
if j.Metadata == nil {
return roles
}
results := j.config.RolesPath.Get(*j.Metadata)
switch rs := results[0].(type) {
case []interface{}:
roles = rs
default:
return roles
}
return roles
}
func (j *JWT) HasReadRole() bool {
roles := j.roles()
for _, v := range roles {
for _, r := range j.config.ReadOnlyRoles {
if v == r {
return true
}
}
}
return false
}
func (j *JWT) HasAdminRole() bool {
roles := j.roles()
for _, v := range roles {
for _, r := range j.config.AdminRoles {
if v == r {
return true
}
}
}
return false
}