Backend: Support encrypted password (#231)

See issue #221, only handles bcrypt
This commit is contained in:
agolebiowska 2020-01-28 11:04:10 +01:00 committed by Michael Mayer
parent e594123a0c
commit 81a587aa19
3 changed files with 67 additions and 1 deletions

View file

@ -20,7 +20,7 @@ func CreateSession(router *gin.RouterGroup, conf *config.Config) {
return
}
if f.Password != conf.AdminPassword() {
if !conf.CheckPassword(f.Password) {
c.AbortWithStatusJSON(400, gin.H{"error": "Invalid password"})
return
}

26
internal/config/utils.go Normal file
View file

@ -0,0 +1,26 @@
package config
import (
"regexp"
"golang.org/x/crypto/bcrypt"
)
func isBcrypt(s string) bool {
b, err := regexp.MatchString(`^\$2[ayb]\$.{56}$`, s)
if err != nil {
return false
}
return b
}
func (c *Config) CheckPassword(p string) bool {
ap := c.AdminPassword()
if isBcrypt(ap) {
err := bcrypt.CompareHashAndPassword([]byte(ap), []byte(p))
return err == nil
}
return ap == p
}

View file

@ -0,0 +1,40 @@
package config
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestUtils_CheckPassword(t *testing.T) {
ctx := CliTestContext()
c := NewConfig(ctx)
formPassword := "photoprism"
c.config.AdminPassword = "$2b$10$cRhWIleqJkbaFWhBMp54VOI25RvVubxOooCWzWgdrvl5COFxaBnAy"
check := c.CheckPassword(formPassword)
assert.True(t, check)
c.config.AdminPassword = "photoprism"
check = c.CheckPassword(formPassword)
assert.True(t, check)
c.config.AdminPassword = "$2b$10$yprZEQzm/Qy7AaePXtKfkem0kANBZgRwl8HbLE4JrjK6/8Pypgi1W"
check = c.CheckPassword(formPassword)
assert.False(t, check)
c.config.AdminPassword = "admin"
check = c.CheckPassword(formPassword)
assert.False(t, check)
}
func TestUtils_isBcrypt(t *testing.T) {
p := "$2b$10$cRhWIleqJkbaFWhBMp54VOI25RvVubxOooCWzWgdrvl5COFxaBnAy"
assert.True(t, isBcrypt(p))
p = "$2b$10$cRhWIleqJkbaFWhBMp54VOI25RvVubxOooCWzWgdrvl5COFxaBnA"
assert.False(t, isBcrypt(p))
p = "admin"
assert.False(t, isBcrypt(p))
}