This repository has been archived by the owner on Oct 17, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauthenticator.go
116 lines (100 loc) · 2.41 KB
/
authenticator.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
package authenticator
import (
"encoding/base64"
"errors"
"fmt"
"net/http"
"strings"
"time"
"github.com/aofei/air"
)
// BasicAuthGasConfig is a set of configurations for the `BasicAuthGas`.
type BasicAuthGasConfig struct {
Validator func(username, password string, req *air.Request, res *air.Response) (bool, error)
Realm string
ErrUnauthorized error
Skippable func(*air.Request, *air.Response) bool
}
// BasicAuthGas returns an `air.Gas` that is used to authenticate ervery request
// by using the HTTP Basic Authentication (See RFC 2617, Section 2) based on the
// bagc. It prevents unauthenticated clients from accessing server resources.
func BasicAuthGas(bagc BasicAuthGasConfig) air.Gas {
if bagc.Validator == nil {
bagc.Validator = func(
_ string,
_ string,
_ *air.Request,
_ *air.Response,
) (bool, error) {
return false, nil
}
}
if bagc.ErrUnauthorized == nil {
bagc.ErrUnauthorized = errors.New(
http.StatusText(http.StatusUnauthorized),
)
}
return func(next air.Handler) air.Handler {
return func(req *air.Request, res *air.Response) error {
if bagc.Skippable != nil && bagc.Skippable(req, res) {
return next(req, res)
}
authHeader := req.Header.Get("Authorization")
if len(authHeader) < 6 ||
!strings.EqualFold(authHeader[:6], "Basic ") {
res.Status = http.StatusUnauthorized
if bagc.Realm != "" {
res.Header.Set(
"WWW-Authenticate",
fmt.Sprintf(
"Basic realm=%q",
bagc.Realm,
),
)
}
return bagc.ErrUnauthorized
}
b, _ := base64.StdEncoding.DecodeString(authHeader[6:])
authParts := strings.SplitN(string(b), ":", 2)
if len(authParts) != 2 ||
authParts[0] == "" ||
authParts[1] == "" {
res.Status = http.StatusUnauthorized
if bagc.Realm != "" {
res.Header.Set(
"WWW-Authenticate",
fmt.Sprintf(
"Basic realm=%q",
bagc.Realm,
),
)
}
return bagc.ErrUnauthorized
}
authorized, err := bagc.Validator(
authParts[0],
authParts[1],
req,
res,
)
if err != nil {
return err
}
if !authorized {
time.Sleep(3 * time.Second)
res.Status = http.StatusUnauthorized
if bagc.Realm != "" {
res.Header.Set(
"WWW-Authenticate",
fmt.Sprintf(
"Basic realm=%q",
bagc.Realm,
),
)
}
return bagc.ErrUnauthorized
}
return next(req, res)
}
}
}