Compare commits

..

1 Commits

Author SHA1 Message Date
Nagy Károly Gábriel 232d15fb3d htpasswd: implement routines for working with .htpasswd
Signed-off-by: Nagy Károly Gábriel <k@jpi.io>
2023-09-22 11:07:17 +03:00
2 changed files with 28 additions and 5 deletions
+12 -5
View File
@@ -142,20 +142,26 @@ func DeleteUser(file, user string) error {
} }
// VerifyUser will check if the given user and password are matching // VerifyUser will check if the given user and password are matching
// with the contect of the given file // with the content of the given file
func VerifyUser(file, user, passwd string) error { func VerifyUser(file, user, passwd string) error {
pp, err := ParseHtpasswdFile(file) pp, err := ParseHtpasswdFile(file)
if err != nil { if err != nil {
return err return err
} }
if _, ok := pp[user]; !ok { return pp.Verify(user, passwd)
}
// Verify will check if the given user and password are matching
// with the given Passwd object content
func (pp *Passwds) Verify(user, passwd string) error {
if _, ok := (*pp)[user]; !ok {
return fmt.Errorf("user %s does not exist", user) return fmt.Errorf("user %s does not exist", user)
} }
alg, err := identifyHash(pp[user]) alg, err := identifyHash((*pp)[user])
if err != nil { if err != nil {
return fmt.Errorf("cannot identify algo %v", alg) return fmt.Errorf("cannot identify algo %v", alg)
} }
return verifyPass(passwd, pp[user], alg) return verifyPass(passwd, (*pp)[user], alg)
} }
func verifyPass(pass, hash string, alg HashAlgorithm) error { func verifyPass(pass, hash string, alg HashAlgorithm) error {
@@ -239,7 +245,8 @@ func (pp *Passwds) toByte() []byte {
func identifyHash(h string) (HashAlgorithm, error) { func identifyHash(h string) (HashAlgorithm, error) {
switch { switch {
case strings.HasPrefix(h, "$2a$"), strings.HasPrefix(h, "$2y$"), strings.HasPrefix(h, "$2x$"), strings.HasPrefix(h, "$2b$"): case strings.HasPrefix(h, "$2a$"), strings.HasPrefix(h, "$2y$"),
strings.HasPrefix(h, "$2x$"), strings.HasPrefix(h, "$2b$"):
return HashBCrypt, nil return HashBCrypt, nil
case strings.HasPrefix(h, "$apr1$"): case strings.HasPrefix(h, "$apr1$"):
return HashAPR1, nil return HashAPR1, nil
+16
View File
@@ -72,3 +72,19 @@ func TestVerifyPassword(t *testing.T) {
} }
} }
} }
func TestVerify(t *testing.T) {
f, err := os.Stat("htpasswd_testdata")
if err != nil {
TestCreateUser(t)
}
pp, err := ParseHtpasswdFile(f.Name())
if err != nil {
t.Fatal(err)
}
err = pp.Verify("bcrypt", "123456@")
if err != nil {
t.Fatalf(err.Error())
}
}