fix: /login now has better error handling/reporting

This commit is contained in:
2026-09-01 15:38:17 +02:00
parent b35dc4841f
commit 26aa0c2a94
3 changed files with 18 additions and 2 deletions
+9 -1
View File
@@ -1,6 +1,7 @@
package handler package handler
import ( import (
"errors"
"log/slog" "log/slog"
"net/http" "net/http"
@@ -41,8 +42,15 @@ func (h *AuthHandler) Login(w http.ResponseWriter, r *http.Request) {
tokens, err := h.AuthService.Login(ctx, payload.Email, payload.Password) tokens, err := h.AuthService.Login(ctx, payload.Email, payload.Password)
if err != nil { if err != nil {
slog.ErrorContext(ctx, "failed to login", slog.Any("error", err)) if errors.Is(err, domain.ErrEmailNotFound) {
response.Error(ctx, w, http.StatusUnauthorized, "email not found")
} else if errors.Is(err, domain.ErrPasswordWrong) {
response.Error(ctx, w, http.StatusUnauthorized, "password is wrong")
} else {
response.Error(ctx, w, http.StatusInternalServerError, "failed to login") response.Error(ctx, w, http.StatusInternalServerError, "failed to login")
}
slog.ErrorContext(ctx, "failed to login", slog.Any("error", err))
return return
} }
+6 -1
View File
@@ -14,6 +14,11 @@ import (
"golang.org/x/crypto/bcrypt" "golang.org/x/crypto/bcrypt"
) )
var (
ErrEmailNotFound = errors.New("email not found")
ErrPasswordWrong = errors.New("password is wrong")
)
type AuthRepository interface { type AuthRepository interface {
GetUserById(ctx context.Context, id string) (*AuthUser, error) GetUserById(ctx context.Context, id string) (*AuthUser, error)
GetUserByEmail(ctx context.Context, email string) (*AuthUser, error) GetUserByEmail(ctx context.Context, email string) (*AuthUser, error)
@@ -71,7 +76,7 @@ func (s *AuthService) Authenticate(ctx context.Context, email string, password s
err = bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(password)) err = bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(password))
if err != nil { if err != nil {
if errors.Is(err, bcrypt.ErrMismatchedHashAndPassword) { if errors.Is(err, bcrypt.ErrMismatchedHashAndPassword) {
return user, errors.New("invalid email or password") return user, ErrPasswordWrong
} }
return user, err return user, err
} }
+3
View File
@@ -36,6 +36,9 @@ func (r *AuthRepo) GetUserByEmail(ctx context.Context, email string) (*domain.Au
email, email,
).Scan(&user.ID, &user.Email, &user.Name, &user.PasswordHash) ).Scan(&user.ID, &user.Email, &user.Name, &user.PasswordHash)
if err != nil { if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return nil, domain.ErrEmailNotFound
}
return nil, fmt.Errorf("failed to get user: %w", err) return nil, fmt.Errorf("failed to get user: %w", err)
} }