aboutsummaryrefslogtreecommitdiffstats
path: root/backend/internal/router/router.go
blob: b82e1af62cce23af311c3325560c884ae121a3d0 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package router

import (
	"finance/backend/internal/api/auth"
	"finance/backend/internal/api/v1/users"
	"finance/backend/internal/config"
	"finance/backend/internal/database"
	"net/http"

	"github.com/gin-gonic/gin"
)

// SetupRouter configures the API routes
func SetupRouter(cfg *config.Config) *gin.Engine {
	r := gin.Default()

	// Enable CORS
	r.Use(func(c *gin.Context) {
		c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
		c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
		c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
		c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT, DELETE")

		if c.Request.Method == "OPTIONS" {
			c.AbortWithStatus(204)
			return
		}

		c.Next()
	})

	// Public utility endpoints
	r.GET("/ping", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{
			"message": "pong",
		})
	})

	// Add database status endpoint
	r.GET("/db-status", func(c *gin.Context) {
		// Try to get a connection from the pool
		sqlDB, err := database.DB.DB()
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{
				"status":  "error",
				"message": "Failed to get database connection",
				"error":   err.Error(),
			})
			return
		}

		// Check if database is reachable
		err = sqlDB.Ping()
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{
				"status":  "error",
				"message": "Database is not reachable",
				"error":   err.Error(),
			})
			return
		}

		c.JSON(http.StatusOK, gin.H{
			"status":  "success",
			"message": "Database connection is healthy",
		})
	})

	// API v1 routes
	v1 := r.Group("/api/v1")
	{
		// Auth routes (public)
		v1.POST("/auth/signup", auth.Signup(cfg))
		v1.POST("/auth/login", auth.Login(cfg))

		// Protected routes
		protected := v1.Group("")
		protected.Use(auth.AuthMiddleware(cfg))
		{
			// User routes
			protected.GET("/users/me", users.GetCurrentUser)

			// Add other protected routes here
		}
	}

	return r
}