diff --git a/internal/handler/handler.go b/internal/handler/handler.go index 73e2d03..36f14e9 100644 --- a/internal/handler/handler.go +++ b/internal/handler/handler.go @@ -35,7 +35,13 @@ func (h *Handler) Register(w http.ResponseWriter, r *http.Request) { return } - user, err := h.Repository.AddUser(context.Background(), c.Login, c.Password) + pass, err := util.StringToHash(c.Password) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + return + } + + user, err := h.Repository.AddUser(context.Background(), c.Login, pass) if err != nil { var e *pgconn.PgError if errors.As(err, &e) && e.Code == "23505" { @@ -78,7 +84,7 @@ func (h *Handler) Login(w http.ResponseWriter, r *http.Request) { return } - if user.Password != c.Password { + if !util.CheckPassword(user.Password, c.Password) { w.WriteHeader(http.StatusUnauthorized) return } diff --git a/internal/util/hash.go b/internal/util/hash.go new file mode 100644 index 0000000..825b477 --- /dev/null +++ b/internal/util/hash.go @@ -0,0 +1,17 @@ +package util + +import "golang.org/x/crypto/bcrypt" + +func StringToHash(password string) (string, error) { + bytePassword := []byte(password) + hash, err := bcrypt.GenerateFromPassword(bytePassword, bcrypt.DefaultCost) + if err != nil { + return "", err + } + return string(hash), nil +} + +func CheckPassword(hashPassword, password string) bool { + err := bcrypt.CompareHashAndPassword([]byte(hashPassword), []byte(password)) + return err == nil +}