Skip to content

Commit 9f79d7d

Browse files
committed
instanciar handlers
1 parent 087c52f commit 9f79d7d

File tree

4 files changed

+54
-29
lines changed

4 files changed

+54
-29
lines changed

cmd/main.go

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ func main() {
3434
}
3535
defer dbPool.Close()
3636

37+
// Instantiate repositories
3738
userRepo := users.NewPostgresUserRepository(dbPool)
3839
productRepo := products.NewPostgresProductRepository(dbPool)
3940
categoryRepo := categories.NewPostgresCategoryRepository(dbPool)
@@ -44,13 +45,15 @@ func main() {
4445
// Instantiate the password hasher
4546
hasher := auth.NewBcryptPasswordHasher()
4647

47-
// Pass the hasher to NewAuthHandler
48+
// Instantiate handlers
4849
authHandler := handlers.NewAuthHandler(userRepo, hasher, cfg.JWTSecret, defaultJWTExpiry)
4950
userHandler := handlers.NewUserHandler(userRepo, addressRepo)
5051
productHandler := handlers.NewProductHandler(productRepo)
5152
categoryHandler := handlers.NewCategoryHandler(categoryRepo)
5253
cartHandler := handlers.NewCartHandler(cartRepo, productRepo)
5354
orderHandler := handlers.NewOrderHandler(orderRepo, cartRepo, addressRepo)
55+
56+
// Instantiate middleware
5457
authMiddleware := auth.NewMiddleware(cfg.JWTSecret, userRepo)
5558

5659
r := setupRoutes(authHandler, userHandler, productHandler, categoryHandler, cartHandler, orderHandler, authMiddleware)
@@ -60,6 +63,7 @@ func main() {
6063
port = defaultPort
6164
}
6265

66+
// Configure HTTP server
6367
srv := &http.Server{
6468
Addr: ":" + port,
6569
Handler: r,
@@ -68,19 +72,23 @@ func main() {
6872
IdleTimeout: 15 * time.Second,
6973
}
7074

75+
// Setup graceful shutdown
7176
done := make(chan os.Signal, 1)
7277
signal.Notify(done, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)
7378

79+
// Start server in a goroutine
7480
go func() {
7581
log.Printf("Server starting on port %s", port)
7682
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
7783
log.Fatalf("listen: %s\n", err)
7884
}
7985
}()
8086

87+
// Wait for shutdown signal
8188
<-done
8289
log.Println("Server shutting down gracefully...")
8390

91+
// Create context for shutdown
8492
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
8593
defer cancel()
8694

@@ -91,11 +99,13 @@ func main() {
9199
log.Println("Server exited properly")
92100
}
93101

102+
// setupRoutes configures the API routes using mux router.
94103
func setupRoutes(ah *handlers.AuthHandler, uh *handlers.UserHandler, ph *handlers.ProductHandler, ch *handlers.CategoryHandler, cartH *handlers.CartHandler, oh *handlers.OrderHandler, mw *auth.Middleware) *mux.Router {
95104
r := mux.NewRouter()
96105

97106
apiV1 := r.PathPrefix("/api").Subrouter()
98107

108+
// Public routes
99109
apiV1.HandleFunc("/health", handlers.HealthCheck).Methods("GET")
100110
apiV1.HandleFunc("/auth/register", ah.Register).Methods("POST")
101111
apiV1.HandleFunc("/auth/login", ah.Login).Methods("POST")
@@ -104,6 +114,7 @@ func setupRoutes(ah *handlers.AuthHandler, uh *handlers.UserHandler, ph *handler
104114
apiV1.HandleFunc("/categories", ch.GetAllCategories).Methods("GET")
105115
apiV1.HandleFunc("/categories/{id:[0-9a-fA-F-]+}", ch.GetCategory).Methods("GET")
106116

117+
// Protected routes (grouped by resource)
107118
protectedUserRoutes := apiV1.PathPrefix("/users").Subrouter()
108119
protectedUserRoutes.Use(mw.Authenticate)
109120
protectedUserRoutes.HandleFunc("/me", uh.GetMe).Methods("GET")

internal/handlers/auth_handler.go

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,6 @@ func (h *AuthHandler) Register(w http.ResponseWriter, r *http.Request) {
8181
return
8282
}
8383

84-
// Hash the password using the injected hasher
8584
hashedPassword, err := h.Hasher.HashPassword(req.Password)
8685
if err != nil {
8786
webutils.ErrorJSON(w, errors.New("failed to register user"), http.StatusInternalServerError)
@@ -94,7 +93,6 @@ func (h *AuthHandler) Register(w http.ResponseWriter, r *http.Request) {
9493
PasswordHash: hashedPassword,
9594
}
9695

97-
// Call UserRepo.Create with individual fields as per current repo signature
9896
createdUser, err := h.UserRepo.Create(context.Background(), user.Name, user.Email, user.PasswordHash)
9997
if err != nil {
10098
webutils.ErrorJSON(w, errors.New("failed to register user"), http.StatusInternalServerError)
@@ -133,14 +131,12 @@ func (h *AuthHandler) Login(w http.ResponseWriter, r *http.Request) {
133131
return
134132
}
135133

136-
// Check the password using the injected hasher
137134
err = h.Hasher.CheckPassword(user.PasswordHash, req.Password)
138-
if err != nil { // bcrypt.CompareHashAndPassword returns error on mismatch
135+
if err != nil {
139136
webutils.ErrorJSON(w, errors.New("invalid email or password"), http.StatusUnauthorized)
140137
return
141138
}
142139

143-
// Generate JWT using the correct function name
144140
token, err := auth.GenerateToken(user.ID, h.JwtSecret, h.TokenExpiryDuration)
145141
if err != nil {
146142
webutils.ErrorJSON(w, errors.New("login failed"), http.StatusInternalServerError)

internal/handlers/product_handler_test.go

Lines changed: 0 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -20,20 +20,6 @@ import (
2020
"github.com/stretchr/testify/mock"
2121
)
2222

23-
// --- Test Setup Helpers ---
24-
25-
// setupBaseTest creates common mocks and components for handler tests.
26-
func setupBaseTest(t *testing.T) (*users.MockUserRepository, *auth.Middleware, *mux.Router) {
27-
mockUserRepo := new(users.MockUserRepository)
28-
// Use a fixed test secret for predictable tokens
29-
testJwtSecret := "test-secret-for-jwt-please-change"
30-
authMiddleware := auth.NewMiddleware(testJwtSecret, mockUserRepo)
31-
32-
router := mux.NewRouter()
33-
34-
return mockUserRepo, authMiddleware, router
35-
}
36-
3723
// setupProductTest creates mock repositories, handler, middleware, and router for tests.
3824
func setupProductTest(t *testing.T) (*products.MockProductRepository, *users.MockUserRepository, *handlers.ProductHandler, *auth.Middleware, *mux.Router) {
3925
mockProductRepo := new(products.MockProductRepository)
@@ -187,15 +173,6 @@ func TestProductHandler_GetProduct(t *testing.T) {
187173

188174
// --- Tests for Protected Routes (Require Authentication) ---
189175

190-
// Helper to generate a test token
191-
func generateTestToken(userID uuid.UUID, secret string) string {
192-
token, err := auth.GenerateToken(userID, secret, time.Hour)
193-
if err != nil {
194-
panic("failed to generate test token: " + err.Error()) // Panic in test setup is ok
195-
}
196-
return token
197-
}
198-
199176
func TestProductHandler_CreateProduct(t *testing.T) {
200177
// Removed setup from here
201178
testUserID := uuid.New()
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package handlers_test
2+
3+
import (
4+
"bullet-cloud-api/internal/auth"
5+
"bullet-cloud-api/internal/users"
6+
"testing"
7+
"time"
8+
9+
"github.com/google/uuid"
10+
"github.com/gorilla/mux"
11+
)
12+
13+
// --- Common Test Setup --- //
14+
15+
const testJwtSecret = "test-secret-for-jwt-please-change" // Consistent secret for tests
16+
17+
// setupBaseTest initializes common components for handler tests:
18+
// - MockUserRepository
19+
// - AuthMiddleware (configured with test secret and user repo)
20+
// - Mux Router
21+
func setupBaseTest(t *testing.T) (*users.MockUserRepository, *auth.Middleware, *mux.Router) {
22+
t * testing.T // Ensure t is used or remove if not needed directly
23+
mockUserRepo := new(users.MockUserRepository)
24+
// Use a fixed expiry for consistency in tests, can be overridden if needed
25+
authMiddleware := auth.NewMiddleware(testJwtSecret, mockUserRepo)
26+
router := mux.NewRouter()
27+
28+
return mockUserRepo, authMiddleware, router
29+
}
30+
31+
// generateTestToken creates a JWT for testing purposes.
32+
func generateTestToken(userID uuid.UUID, secret string) string {
33+
// Use a fixed expiry for consistency unless specific test requires different
34+
tokenExpiry := time.Hour * 1
35+
token, err := auth.GenerateToken(userID, secret, tokenExpiry)
36+
if err != nil {
37+
// Panic is acceptable in test setup if token generation fails fundamentally
38+
panic("Failed to generate test token: " + err.Error())
39+
}
40+
return token
41+
}

0 commit comments

Comments
 (0)