-
Notifications
You must be signed in to change notification settings - Fork 0
/
http.go
90 lines (77 loc) · 1.77 KB
/
http.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 auth
import (
"bytes"
"context"
"encoding/json"
"net/http"
"github.com/dolfly/core/auth"
"github.com/dolfly/core/logger"
ctxvalue "github.com/dolfly/x/ctx"
"github.com/dolfly/x/internal/plugin"
)
type httpPluginRequest struct {
Username string `json:"username"`
Password string `json:"password"`
Client string `json:"client"`
}
type httpPluginResponse struct {
OK bool `json:"ok"`
ID string `json:"id"`
}
type httpPlugin struct {
url string
client *http.Client
header http.Header
log logger.Logger
}
// NewHTTPPlugin creates an Authenticator plugin based on HTTP.
func NewHTTPPlugin(name string, url string, opts ...plugin.Option) auth.Authenticator {
var options plugin.Options
for _, opt := range opts {
opt(&options)
}
return &httpPlugin{
url: url,
client: plugin.NewHTTPClient(&options),
header: options.Header,
log: logger.Default().WithFields(map[string]any{
"kind": "auther",
"auther": name,
}),
}
}
func (p *httpPlugin) Authenticate(ctx context.Context, user, password string, opts ...auth.Option) (id string, ok bool) {
if p.client == nil {
return
}
rb := httpPluginRequest{
Username: user,
Password: password,
Client: string(ctxvalue.ClientAddrFromContext(ctx)),
}
v, err := json.Marshal(&rb)
if err != nil {
return
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, p.url, bytes.NewReader(v))
if err != nil {
return
}
if p.header != nil {
req.Header = p.header.Clone()
}
req.Header.Set("Content-Type", "application/json")
resp, err := p.client.Do(req)
if err != nil {
return
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return
}
res := httpPluginResponse{}
if err := json.NewDecoder(resp.Body).Decode(&res); err != nil {
return
}
return res.ID, res.OK
}