Added transactions and improved error handling #35
@@ -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
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user