1
0
mirror of https://github.com/oauth2-proxy/oauth2-proxy.git synced 2024-11-28 09:08:44 +02:00
oauth2-proxy/htpasswd.go

60 lines
1.2 KiB
Go
Raw Normal View History

2012-12-11 04:59:23 +03:00
package main
import (
"crypto/sha1"
"encoding/base64"
"encoding/csv"
2012-12-17 21:38:33 +03:00
"io"
2012-12-11 04:59:23 +03:00
"log"
"os"
)
// lookup passwords in a htpasswd file
// The entries must have been created with -s for SHA encryption
type HtpasswdFile struct {
Users map[string]string
}
2012-12-17 21:38:33 +03:00
func NewHtpasswdFromFile(path string) (*HtpasswdFile, error) {
2012-12-11 04:59:23 +03:00
r, err := os.Open(path)
if err != nil {
2012-12-17 21:38:33 +03:00
return nil, err
2012-12-11 04:59:23 +03:00
}
2012-12-17 21:38:33 +03:00
return NewHtpasswd(r)
}
func NewHtpasswd(file io.Reader) (*HtpasswdFile, error) {
csv_reader := csv.NewReader(file)
2012-12-11 04:59:23 +03:00
csv_reader.Comma = ':'
csv_reader.Comment = '#'
csv_reader.TrimLeadingSpace = true
records, err := csv_reader.ReadAll()
if err != nil {
2012-12-17 21:38:33 +03:00
return nil, err
2012-12-11 04:59:23 +03:00
}
h := &HtpasswdFile{Users: make(map[string]string)}
for _, record := range records {
h.Users[record[0]] = record[1]
}
2012-12-17 21:38:33 +03:00
return h, nil
2012-12-11 04:59:23 +03:00
}
func (h *HtpasswdFile) Validate(user string, password string) bool {
realPassword, exists := h.Users[user]
if !exists {
return false
}
if realPassword[:5] == "{SHA}" {
d := sha1.New()
d.Write([]byte(password))
if realPassword[5:] == base64.StdEncoding.EncodeToString(d.Sum(nil)) {
return true
}
} else {
log.Printf("Invalid htpasswd entry for %s. Must be a SHA entry.", user)
}
return false
}