-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.go
More file actions
56 lines (48 loc) · 1.5 KB
/
auth.go
File metadata and controls
56 lines (48 loc) · 1.5 KB
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
package echobasicauth
import (
"net"
"slices"
"sync"
)
// Auth model
type Auth struct {
Login string `json:"login" yaml:"login"` // Basic auth login
Password string `json:"password" yaml:"password"` //nolint:gosec // this is an auth model, the field is intentional
IPs []string `json:"ips" yaml:"ips"` // Allowed IPs and CIDRs
parsedIPs []string // lazily parsed plain IPs from the IPs field, used by AllowedIP
parsedCIDRs []*net.IPNet // lazily parsed CIDRs from the IPs field, used by AllowedIP
parseOnce sync.Once // ensures IPs are parsed only once, even under concurrent access
}
// parseIPs parses the IPs and CIDRs from the IPs field into internal state (called once lazily)
func (a *Auth) parseIPs() {
a.parseOnce.Do(func() {
a.parsedIPs = []string{}
a.parsedCIDRs = []*net.IPNet{}
for _, ip := range a.IPs {
if _, ipnet, err := net.ParseCIDR(ip); err == nil {
a.parsedCIDRs = append(a.parsedCIDRs, ipnet)
} else if net.ParseIP(ip) != nil {
a.parsedIPs = append(a.parsedIPs, ip)
}
}
})
}
// AllowedIP checks if the given IP is allowed by this Auth's IP rules
func (a *Auth) AllowedIP(ip string) bool {
a.parseIPs()
if len(a.parsedIPs) == 0 && len(a.parsedCIDRs) == 0 {
return true
}
if len(a.parsedIPs) != 0 && slices.Contains(a.parsedIPs, ip) {
return true
}
if len(a.parsedCIDRs) != 0 {
parsed := net.ParseIP(ip)
for _, ipnet := range a.parsedCIDRs {
if ipnet.Contains(parsed) {
return true
}
}
}
return false
}