git.iko.soy/typeable/oauth2-proxy
on v2.2 help sign in
60 lines 1.2 kB history raw
1package main
3import (
4 "crypto/sha1"
5 "encoding/base64"
6 "encoding/csv"
7 "io"
8 "log"
9 "os"
12// lookup passwords in a htpasswd file
13// The entries must have been created with -s for SHA encryption
15type HtpasswdFile struct {
16 Users map[string]string
19func NewHtpasswdFromFile(path string) (*HtpasswdFile, error) {
20 r, err := os.Open(path)
21 if err != nil {
22 return nil, err
23 }
24 defer r.Close()
25 return NewHtpasswd(r)
28func NewHtpasswd(file io.Reader) (*HtpasswdFile, error) {
29 csv_reader := csv.NewReader(file)
30 csv_reader.Comma = ':'
31 csv_reader.Comment = '#'
32 csv_reader.TrimLeadingSpace = true
34 records, err := csv_reader.ReadAll()
35 if err != nil {
36 return nil, err
37 }
38 h := &HtpasswdFile{Users: make(map[string]string)}
39 for _, record := range records {
40 h.Users[record[0]] = record[1]
41 }
42 return h, nil
45func (h *HtpasswdFile) Validate(user string, password string) bool {
46 realPassword, exists := h.Users[user]
47 if !exists {
48 return false
49 }
50 if realPassword[:5] == "{SHA}" {
51 d := sha1.New()
52 d.Write([]byte(password))
53 if realPassword[5:] == base64.StdEncoding.EncodeToString(d.Sum(nil)) {
54 return true
55 }
56 } else {
57 log.Printf("Invalid htpasswd entry for %s. Must be a SHA entry.", user)
58 }
59 return false