1
0
mirror of https://github.com/muety/wakapi.git synced 2023-08-10 21:12:56 +03:00

feat: add auto-migrations for old md5 password to maintain backwards compatibility

This commit is contained in:
Ferdinand Mütsch
2020-05-25 22:24:29 +02:00
parent 08675bd99f
commit 6c2f0cb1ec
5 changed files with 67 additions and 14 deletions

View File

@ -1,7 +1,9 @@
package utils
import (
"crypto/md5"
"encoding/base64"
"encoding/hex"
"errors"
"github.com/muety/wakapi/models"
"golang.org/x/crypto/bcrypt"
@ -10,6 +12,8 @@ import (
"strings"
)
var md5Regex = regexp.MustCompile(`^[a-f0-9]{32}$`)
func ExtractBasicAuth(r *http.Request) (username, password string, err error) {
authHeader := strings.Split(r.Header.Get("Authorization"), " ")
if len(authHeader) != 2 || authHeader[0] != "Basic" {
@ -54,11 +58,25 @@ func ExtractCookieAuth(r *http.Request, config *models.Config) (login *models.Lo
return login, nil
}
func CheckPassword(user *models.User, password, salt string) bool {
func IsMd5(hash string) bool {
return md5Regex.Match([]byte(hash))
}
func CheckPasswordBcrypt(user *models.User, password, salt string) bool {
err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password+salt))
return err == nil
}
// deprecated, only here for backwards compatibility
func CheckPasswordMd5(user *models.User, password string) bool {
hash := md5.Sum([]byte(password))
hashStr := hex.EncodeToString(hash[:])
if hashStr == user.Password {
return true
}
return false
}
// inplace
func HashPassword(u *models.User, salt string) error {
bytes, err := bcrypt.GenerateFromPassword([]byte(u.Password+salt), bcrypt.DefaultCost)