-
Notifications
You must be signed in to change notification settings - Fork 34
/
jwt_auth.go
90 lines (69 loc) · 1.89 KB
/
jwt_auth.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
package jwt
import (
"context"
"strings"
"github.com/pkg/errors"
"github.com/machinefi/w3bstream/pkg/depends/x/contextx"
"github.com/machinefi/w3bstream/pkg/depends/x/misc/must"
)
type Auth struct {
AuthInQuery string `name:"authorization,omitempty" in:"query" validate:"@string[1,]"`
AuthInHeader string `name:"Authorization,omitempty" in:"header" validate:"@string[1,]"`
}
func (r Auth) ContextKey() interface{} { return keyAuth{} }
func (r Auth) Output(ctx context.Context) (pl interface{}, err error) {
jwt, ok := ConfFromContext(ctx)
if !ok {
return nil, ErrEmptyJwtContext
}
av := r.AuthInQuery
if av == "" {
av = r.AuthInHeader
}
tok := strings.TrimSpace(strings.Replace(av, "Bearer", " ", 1))
if BuiltInTokenFn != nil {
if pl, ok = BuiltInTokenFn(tok); ok {
return pl, nil
}
}
claims, err := jwt.ParseToken(tok)
if err != nil {
return nil, err
}
if WithPermissionFn != nil && !WithPermissionFn(claims) {
return nil, ErrNoPermission
}
pl = claims.Payload
return
}
type keyConf struct{}
func WithConfContext(jwt *Jwt) func(context.Context) context.Context {
return func(ctx context.Context) context.Context {
return contextx.WithValue(ctx, keyConf{}, jwt)
}
}
func ConfFromContext(ctx context.Context) (*Jwt, bool) {
j, ok := ctx.Value(keyConf{}).(*Jwt)
return j, ok
}
func MustConfFromContext(ctx context.Context) *Jwt {
j, ok := ctx.Value(keyConf{}).(*Jwt)
must.BeTrue(ok)
return j
}
type keyAuth struct{}
func AuthFromContext(ctx context.Context) interface{} {
return ctx.Value(keyAuth{})
}
var (
ErrEmptyJwtContext = errors.New("empty jwt context")
ErrNoPermission = errors.New("no permission")
)
var BuiltInTokenFn func(string) (interface{}, bool)
func SetBuiltInTokenFn(f func(string) (interface{}, bool)) {
BuiltInTokenFn = f
}
var WithPermissionFn func(*Claims) bool
func SetWithPermissionFn(f func(*Claims) bool) {
WithPermissionFn = f
}