Browse Source

htpasswd: clean up parser

Signed-off-by: Alejandro Mery <amery@jpi.io>
pull/4/head
Alejandro Mery 1 year ago
parent
commit
0fb985026f
  1. 41
      htpasswd/htpasswd.go

41
htpasswd/htpasswd.go

@ -2,7 +2,6 @@
package htpasswd
import (
"errors"
"fmt"
"os"
"strings"
@ -36,29 +35,29 @@ func Parse(htpasswdBytes []byte) (Passwds, error) {
var err error
for lineNumber, line := range lines {
line = strings.Trim(line, " ")
line = strings.TrimSpace(line)
if len(line) == 0 {
// skipping empty lines
continue
}
parts := strings.Split(line, ":")
if ok, err := validLine(parts, lineNumber, line); !ok {
user, password, err := splitLine(line, lineNumber)
if err != nil {
return passwords, err
}
parts = trimParts(parts)
_, exists := passwords[parts[0]]
_, exists := passwords[user]
if exists {
err = &UserError{
Name: parts[0],
Name: user,
Err: ErrExists,
}
return passwords, err
}
passwords[parts[0]] = parts[1]
passwords[user] = password
}
return passwords, err
}
@ -218,20 +217,18 @@ func identifyHash(h string) Hasher {
}
}
func validLine(parts []string, lineNumber int, line string) (bool, error) {
var err error
if len(parts) != 2 {
err = errors.New(fmt.Sprintln("invalid line", lineNumber+1,
"unexpected number of parts split by", ":", len(parts),
"instead of 2 in\"", line, "\""))
return false, err
}
return true, nil
func splitLine(line string, lineNumber int) (user, password string, err error) {
user, password, ok := strings.Cut(line, ":")
if !ok {
return "", "", fmt.Errorf("invalid line %v", lineNumber+1)
}
func trimParts(parts []string) []string {
for i, part := range parts {
parts[i] = strings.Trim(part, " ")
user = strings.TrimSpace(user)
password = strings.TrimSpace(password)
if h := identifyHash(password); h != nil {
return "", "", fmt.Errorf("invalid algorithm on line %v", lineNumber+1)
}
return parts
return user, password, nil
}

Loading…
Cancel
Save