-
Notifications
You must be signed in to change notification settings - Fork 0
/
jwt.go
67 lines (56 loc) · 1.22 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
package jwt
import (
"errors"
"net/http"
"github.com/goa-go/goa"
"github.com/goa-go/goa/utils"
)
// Options is used to declare options, use it by New(jwt.Options{...}).
type Options struct {
Secret interface{}
Unless []string
GetToken func(*goa.Context) string
Verify func(string, interface{}) bool
}
type token struct {
getToken func(*goa.Context) string
verify func(string, interface{}) bool
}
// New returns a jwt middleware for goa.
func New(ops Options) goa.Middleware {
if ops.Secret == nil {
panic(errors.New("require secret"))
}
if str, ok := ops.Secret.(string); ok {
ops.Secret = utils.Str2Bytes(str)
}
s := ops.Secret
token := token{}
if ops.GetToken != nil {
token.getToken = ops.GetToken
} else {
token.getToken = getToken
}
if ops.Verify != nil {
token.verify = ops.Verify
} else {
token.verify = verify
}
return func(c *goa.Context) {
if !include(ops.Unless, c.Path) {
tokenString := token.getToken(c)
if !token.verify(tokenString, s) {
c.Error(http.StatusUnauthorized, http.StatusText(http.StatusUnauthorized))
}
}
c.Next()
}
}
func include(strArray []string, str string) bool {
for _, s := range strArray {
if s == str {
return true
}
}
return false
}