forked from BTBurke/caddy-jwt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.go
117 lines (107 loc) · 2.29 KB
/
config.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
package jwt
import (
"fmt"
"github.com/mholt/caddy/caddy/setup"
"github.com/mholt/caddy/middleware"
)
const (
ALLOW = iota
DENY
)
type JWTAuth struct {
Rules []Rule
Next middleware.Handler
}
type Rule struct {
Path string
AccessRules []AccessRule
}
type AccessRule struct {
Authorize int
Claim string
Value string
}
func Setup(c *setup.Controller) (middleware.Middleware, error) {
rules, err := parse(c)
if err != nil {
return nil, err
}
c.Startup = append(c.Startup, func() error {
fmt.Println("JWT middleware is initiated")
return nil
})
return func(next middleware.Handler) middleware.Handler {
return &JWTAuth{
Rules: rules,
Next: next,
}
}, nil
}
func parse(c *setup.Controller) ([]Rule, error) {
// This parses the following config blocks
/*
jwt /hello
jwt /anotherpath
jwt {
path /hello
path /anotherpath
}
*/
var rules []Rule
for c.Next() {
args := c.RemainingArgs()
switch len(args) {
case 0:
// no argument passed, check the config block
var r = Rule{}
for c.NextBlock() {
switch c.Val() {
case "path":
if !c.NextArg() {
// we are expecting a value
return nil, c.ArgErr()
}
// return error if multiple paths in a block
if len(r.Path) != 0 {
return nil, c.ArgErr()
}
r.Path = c.Val()
if c.NextArg() {
// we are expecting only one value.
return nil, c.ArgErr()
}
case "allow":
args1 := c.RemainingArgs()
if len(args1) != 2 {
return nil, c.ArgErr()
}
r.AccessRules = append(r.AccessRules, AccessRule{Authorize: ALLOW, Claim: args1[0], Value: args1[1]})
case "deny":
args1 := c.RemainingArgs()
if len(args1) != 2 {
return nil, c.ArgErr()
}
r.AccessRules = append(r.AccessRules, AccessRule{Authorize: DENY, Claim: args1[0], Value: args1[1]})
}
}
rules = append(rules, r)
case 1:
rules = append(rules, Rule{Path: args[0]})
// one argument passed
if c.NextBlock() {
// path specified, no block required.
return nil, c.ArgErr()
}
default:
// we want only one argument max
return nil, c.ArgErr()
}
}
// check all rules at least have a path
for _, r := range rules {
if r.Path == "" {
return nil, fmt.Errorf("Each rule must have a path")
}
}
return rules, nil
}