Skip to content

Commit

Permalink
add hash password
Browse files Browse the repository at this point in the history
  • Loading branch information
zelhat committed Jan 10, 2024
1 parent bb4ef51 commit dc1af14
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 2 deletions.
10 changes: 8 additions & 2 deletions internal/handler/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -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" {
Expand Down Expand Up @@ -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
}
Expand Down
17 changes: 17 additions & 0 deletions internal/util/hash.go
Original file line number Diff line number Diff line change
@@ -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
}

0 comments on commit dc1af14

Please sign in to comment.