fix: base64 password hash in file members provider to avoid json issues.

This commit is contained in:
Miroslav Šedivý 2024-02-14 21:45:04 +01:00
parent 9353773bfb
commit ce3830f6a0
2 changed files with 51 additions and 1 deletions

View File

@ -2,6 +2,7 @@ package file
import ( import (
"crypto/sha256" "crypto/sha256"
"encoding/base64"
"encoding/json" "encoding/json"
"io" "io"
"os" "os"
@ -27,7 +28,8 @@ func (provider *MemberProviderCtx) hash(password string) string {
sha256 := sha256.New() sha256 := sha256.New()
sha256.Write([]byte(password)) sha256.Write([]byte(password))
return string(sha256.Sum(nil)) hashedPassword := sha256.Sum(nil)
return base64.StdEncoding.EncodeToString(hashedPassword)
} }
func (provider *MemberProviderCtx) Connect() error { func (provider *MemberProviderCtx) Connect() error {

View File

@ -0,0 +1,48 @@
package file
import (
"encoding/json"
"testing"
"github.com/demodesk/neko/pkg/utils"
)
// Ensure that hashes are the same after encoding and decoding using json
func TestMemberProviderCtx_hash(t *testing.T) {
provider := &MemberProviderCtx{
config: Config{
Hash: true,
},
}
// generate random strings
passwords := []string{}
for i := 0; i < 10; i++ {
password, err := utils.NewUID(32)
if err != nil {
t.Errorf("utils.NewUID() returned error: %s", err)
}
passwords = append(passwords, password)
}
for _, password := range passwords {
hashedPassword := provider.hash(password)
// json encode password hash
hashedPasswordJSON, err := json.Marshal(hashedPassword)
if err != nil {
t.Errorf("json.Marshal() returned error: %s", err)
}
// json decode password hash json
var hashedPasswordStr string
err = json.Unmarshal(hashedPasswordJSON, &hashedPasswordStr)
if err != nil {
t.Errorf("json.Unmarshal() returned error: %s", err)
}
if hashedPasswordStr != hashedPassword {
t.Errorf("hashedPasswordStr: %s != hashedPassword: %s", hashedPasswordStr, hashedPassword)
}
}
}