diff --git a/internal/api/handler/auth.go b/internal/api/handler/auth.go index af924fb..fb9d03b 100644 --- a/internal/api/handler/auth.go +++ b/internal/api/handler/auth.go @@ -1,6 +1,7 @@ package handler import ( + "errors" "log/slog" "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) if err != nil { + 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") + } + slog.ErrorContext(ctx, "failed to login", slog.Any("error", err)) - response.Error(ctx, w, http.StatusInternalServerError, "failed to login") return } diff --git a/internal/domain/auth.go b/internal/domain/auth.go index ba5d141..73070d9 100644 --- a/internal/domain/auth.go +++ b/internal/domain/auth.go @@ -14,6 +14,11 @@ import ( "golang.org/x/crypto/bcrypt" ) +var ( + ErrEmailNotFound = errors.New("email not found") + ErrPasswordWrong = errors.New("password is wrong") +) + type AuthRepository interface { GetUserById(ctx context.Context, id 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)) if err != nil { if errors.Is(err, bcrypt.ErrMismatchedHashAndPassword) { - return user, errors.New("invalid email or password") + return user, ErrPasswordWrong } return user, err } diff --git a/internal/repository/auth.go b/internal/repository/auth.go index 70f910a..d4ed7c1 100644 --- a/internal/repository/auth.go +++ b/internal/repository/auth.go @@ -36,6 +36,9 @@ func (r *AuthRepo) GetUserByEmail(ctx context.Context, email string) (*domain.Au email, ).Scan(&user.ID, &user.Email, &user.Name, &user.PasswordHash) if err != nil { + if errors.Is(err, sql.ErrNoRows) { + return nil, domain.ErrEmailNotFound + } return nil, fmt.Errorf("failed to get user: %w", err) }