git.iko.soy/typeable/oauth2-proxy
on v1.1.1 help sign in
59 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 return NewHtpasswd(r)
27func NewHtpasswd(file io.Reader) (*HtpasswdFile, error) {
28 csv_reader := csv.NewReader(file)
29 csv_reader.Comma = ':'
30 csv_reader.Comment = '#'
31 csv_reader.TrimLeadingSpace = true
33 records, err := csv_reader.ReadAll()
34 if err != nil {
35 return nil, err
36 }
37 h := &HtpasswdFile{Users: make(map[string]string)}
38 for _, record := range records {
39 h.Users[record[0]] = record[1]
40 }
41 return h, nil
44func (h *HtpasswdFile) Validate(user string, password string) bool {
45 realPassword, exists := h.Users[user]
46 if !exists {
47 return false
48 }
49 if realPassword[:5] == "{SHA}" {
50 d := sha1.New()
51 d.Write([]byte(password))
52 if realPassword[5:] == base64.StdEncoding.EncodeToString(d.Sum(nil)) {
53 return true
54 }
55 } else {
56 log.Printf("Invalid htpasswd entry for %s. Must be a SHA entry.", user)
57 }
58 return false