Creating passwordMatches help

This commit is contained in:
2024-08-13 13:58:33 +02:00
parent 4ec1d8c5a2
commit bd5c6b2abc
4 changed files with 34 additions and 2 deletions

View File

@ -251,6 +251,16 @@ func (app *application) CreateAuthToken(w http.ResponseWriter, r *http.Request)
}
// validate the password, send error if invalid password
validPassword, err := app.passwordMatches(user.Password, userInput.Password)
if err != nil {
app.invalidCredentials(w)
return
}
if !validPassword {
app.invalidCredentials(w)
return
}
// generate the token

View File

@ -5,6 +5,8 @@ import (
"errors"
"io"
"net/http"
"golang.org/x/crypto/bcrypt"
)
func (app *application) readJSON(w http.ResponseWriter, r *http.Request, data interface{}) error {
@ -65,6 +67,7 @@ func (app *application) badRequest(w http.ResponseWriter, r *http.Request, err e
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadGateway)
w.Write(out)
return nil
}
@ -83,3 +86,17 @@ func (app *application) invalidCredentials(w http.ResponseWriter) error {
}
return nil
}
func (app *application) passwordMatches(hash, password string) (bool, error) {
err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
if err != nil {
switch {
case errors.Is(err, bcrypt.ErrMismatchedHashAndPassword):
return false, nil
default:
return false, err
}
}
return true, nil
}