-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
115 lines (95 loc) · 2.59 KB
/
main.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
package authredirect
import (
"bytes"
"fmt"
"github.com/caddyserver/caddy/v2"
"github.com/caddyserver/caddy/v2/caddyconfig/caddyfile"
"github.com/caddyserver/caddy/v2/caddyconfig/httpcaddyfile"
"github.com/caddyserver/caddy/v2/modules/caddyhttp"
"github.com/go-resty/resty/v2"
"io"
"net/http"
"time"
)
func init() {
caddy.RegisterModule(AuthRedirect{})
httpcaddyfile.RegisterHandlerDirective("auth_redirect", parseCaddyfile)
}
type AuthRedirect struct {
Url string `json:"url"`
restyClient *resty.Client
}
func (AuthRedirect) CaddyModule() caddy.ModuleInfo {
return caddy.ModuleInfo{
ID: "http.handlers.auth_redirect",
New: func() caddy.Module { return new(AuthRedirect) },
}
}
func (f *AuthRedirect) Provision(c caddy.Context) error {
f.restyClient = resty.New()
f.restyClient.SetTimeout(8 * time.Second)
f.restyClient.SetRedirectPolicy(resty.NoRedirectPolicy())
c.Logger(f).Info(fmt.Sprintf("AuthRedirect: %s", f.Url))
return nil
}
func (f AuthRedirect) ServeHTTP(w http.ResponseWriter, clientReq *http.Request, next caddyhttp.Handler) error {
authReqHeaders := map[string]string{}
for k, v := range clientReq.Header {
for _, v2 := range v {
authReqHeaders[k] = v2
}
}
var resp *resty.Response
var err error
urlParameters := clientReq.URL.Query().Encode()
if clientReq.Method == http.MethodPost {
buf := new(bytes.Buffer)
_, _ = io.Copy(buf, clientReq.Body)
clientReq.Body = io.NopCloser(buf)
resp, err = f.restyClient.R().SetHeaders(authReqHeaders).SetBody(buf.Bytes()).Post(f.Url + "?" + urlParameters)
} else {
resp, err = f.restyClient.R().SetHeaders(authReqHeaders).Get(f.Url + "?" + urlParameters)
}
if err != nil {
return err
}
respStatusCode := resp.StatusCode()
if respStatusCode == http.StatusOK {
return next.ServeHTTP(w, clientReq)
}
for k, v := range resp.Header() {
for _, v2 := range v {
w.Header().Set(k, v2)
}
}
w.WriteHeader(respStatusCode)
_, _ = w.Write(resp.Body())
if err != nil {
return err
}
return nil
}
func (f *AuthRedirect) Validate() error {
if f.Url == "" {
return fmt.Errorf("auth_redirect <url> not specified")
}
return nil
}
func parseCaddyfile(h httpcaddyfile.Helper) (caddyhttp.MiddlewareHandler, error) {
var f AuthRedirect
err := f.UnmarshalCaddyfile(h.Dispenser)
return f, err
}
func (f *AuthRedirect) UnmarshalCaddyfile(d *caddyfile.Dispenser) error {
for d.Next() {
if !d.Args(&f.Url) {
return d.ArgErr()
}
}
return nil
}
var (
_ caddy.Validator = (*AuthRedirect)(nil)
_ caddyhttp.MiddlewareHandler = (*AuthRedirect)(nil)
_ caddy.Provisioner = (*AuthRedirect)(nil)
)