-
Notifications
You must be signed in to change notification settings - Fork 28
/
basic_auth.go
62 lines (49 loc) · 1.06 KB
/
basic_auth.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
package main
import (
"encoding/csv"
"errors"
"io"
"os"
)
type BasicAuthData struct {
user string
password string
}
type basicAuth struct {
users map[string]string
}
func newBasicAuthFromFile(path string) (*basicAuth, error) {
r, err := os.Open(path)
if err != nil {
return nil, err
}
return newBasicAuth(r)
}
func newBasicAuth(file io.Reader) (*basicAuth, error) {
csvReader := csv.NewReader(file)
csvReader.Comma = ':'
csvReader.Comment = '#'
csvReader.TrimLeadingSpace = true
records, err := csvReader.ReadAll()
if err != nil {
return nil, err
}
h := &basicAuth{users: make(map[string]string)}
for _, record := range records {
if len(record) != 2 {
return nil, errors.New("invalid basic auth file format")
}
h.users[record[0]] = record[1]
}
if len(h.users) == 0 {
return nil, errors.New("auth file contains no data")
}
return h, nil
}
func (h *basicAuth) validate(authData *BasicAuthData) bool {
realPassword, exists := h.users[authData.user]
if !exists || realPassword != authData.password {
return false
}
return true
}