Backend: Support encrypted password (#231)
See issue #221, only handles bcrypt
This commit is contained in:
parent
e594123a0c
commit
81a587aa19
3 changed files with 67 additions and 1 deletions
|
@ -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
26
internal/config/utils.go
Normal 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
|
||||
}
|
40
internal/config/utils_test.go
Normal file
40
internal/config/utils_test.go
Normal 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))
|
||||
}
|
Loading…
Reference in a new issue