diff options
Diffstat (limited to 'backend/internal')
-rw-r--r-- | backend/internal/api/auth/auth.go | 247 | ||||
-rw-r--r-- | backend/internal/api/v1/loans/loans.go | 248 | ||||
-rw-r--r-- | backend/internal/api/v1/users/handler.go | 19 | ||||
-rw-r--r-- | backend/internal/config/config.go | 54 | ||||
-rw-r--r-- | backend/internal/database/database.go | 61 | ||||
-rw-r--r-- | backend/internal/models/models.go | 97 | ||||
-rw-r--r-- | backend/internal/router/router.go | 88 |
7 files changed, 814 insertions, 0 deletions
diff --git a/backend/internal/api/auth/auth.go b/backend/internal/api/auth/auth.go new file mode 100644 index 0000000..2f8fa6a --- /dev/null +++ b/backend/internal/api/auth/auth.go @@ -0,0 +1,247 @@ +package auth + +import ( + "finance/backend/internal/config" + "finance/backend/internal/database" + "finance/backend/internal/models" + "fmt" + "net/http" + "strings" + "time" + + "github.com/gin-gonic/gin" + "github.com/golang-jwt/jwt/v5" +) + +// Request and Response Types + +// SignupRequest represents the data needed for registering a new user +type SignupRequest struct { + Name string `json:"name" binding:"required"` + Email string `json:"email" binding:"required,email"` + Password string `json:"password" binding:"required,min=8"` +} + +// LoginRequest represents the data needed for user login +type LoginRequest struct { + Email string `json:"email" binding:"required,email"` + Password string `json:"password" binding:"required"` +} + +// AuthResponse is returned on successful authentication +type AuthResponse struct { + Token string `json:"token"` + User models.User `json:"user"` +} + +// JWT Token Functions + +// GenerateJWT creates a new JWT token for a given user ID. +func GenerateJWT(userID uint, cfg *config.Config) (string, error) { + // Create the claims + claims := jwt.MapClaims{ + "sub": userID, // Subject (user ID) + "iss": "finance-app", // Issuer + "aud": "finance-app-users", // Audience + "exp": time.Now().Add(time.Hour * 24).Unix(), // Expiration time (e.g., 24 hours) + "iat": time.Now().Unix(), // Issued at + } + + // Create token + token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) + + // Sign token with secret + signedToken, err := token.SignedString([]byte(cfg.JWTSecret)) + if err != nil { + return "", fmt.Errorf("failed to sign token: %w", err) + } + + return signedToken, nil +} + +// ValidateJWT validates a JWT token and extracts the user ID from it. +// Returns the user ID if the token is valid, or an error if it's not. +func ValidateJWT(tokenString string, cfg *config.Config) (uint, error) { + // Parse the token + token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) { + // Validate the signing method + if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok { + return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"]) + } + + // Return the secret key + return []byte(cfg.JWTSecret), nil + }) + + if err != nil { + return 0, fmt.Errorf("failed to parse token: %w", err) + } + + // Check if token is valid + if !token.Valid { + return 0, fmt.Errorf("invalid token") + } + + // Extract claims + claims, ok := token.Claims.(jwt.MapClaims) + if !ok { + return 0, fmt.Errorf("invalid token claims") + } + + // Verify expiration time + if exp, ok := claims["exp"].(float64); ok { + if time.Now().Unix() > int64(exp) { + return 0, fmt.Errorf("token expired") + } + } else { + return 0, fmt.Errorf("invalid expiration claim") + } + + // Extract user ID from subject claim + sub, ok := claims["sub"].(float64) + if !ok { + return 0, fmt.Errorf("invalid subject claim") + } + + // Convert to uint and return + return uint(sub), nil +} + +// Handler Functions + +// Signup handles user registration +func Signup(cfg *config.Config) gin.HandlerFunc { + return func(c *gin.Context) { + var req SignupRequest + if err := c.ShouldBindJSON(&req); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + return + } + + // Check if user with this email already exists + var existingUser models.User + result := database.DB.Where("email = ?", req.Email).First(&existingUser) + if result.RowsAffected > 0 { + c.JSON(http.StatusBadRequest, gin.H{"error": "User with this email already exists"}) + return + } + + // Create new user + user := models.User{ + Name: req.Name, + Email: req.Email, + } + + // Set password (this will hash it) + if err := user.SetPassword(req.Password); err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to process password"}) + return + } + + // Save user to database + if err := database.DB.Create(&user).Error; err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to create user"}) + return + } + + // Generate JWT token + token, err := GenerateJWT(user.ID, cfg) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to generate authentication token"}) + return + } + + // Clear password hash before returning user data + user.PasswordHash = "" + + c.JSON(http.StatusCreated, AuthResponse{ + Token: token, + User: user, + }) + } +} + +// Login handles user authentication +func Login(cfg *config.Config) gin.HandlerFunc { + return func(c *gin.Context) { + var req LoginRequest + if err := c.ShouldBindJSON(&req); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + return + } + + // Find user by email + var user models.User + result := database.DB.Where("email = ?", req.Email).First(&user) + if result.Error != nil { + c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid email or password"}) + return + } + + // Check password + if err := user.CheckPassword(req.Password); err != nil { + c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid email or password"}) + return + } + + // Generate JWT token + token, err := GenerateJWT(user.ID, cfg) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to generate authentication token"}) + return + } + + // Clear password hash before returning user data + user.PasswordHash = "" + + c.JSON(http.StatusOK, AuthResponse{ + Token: token, + User: user, + }) + } +} + +// AuthMiddleware validates JWT tokens and adds user data to the context +func AuthMiddleware(cfg *config.Config) gin.HandlerFunc { + return func(c *gin.Context) { + authHeader := c.GetHeader("Authorization") + if authHeader == "" { + c.JSON(http.StatusUnauthorized, gin.H{"error": "Authorization header is required"}) + c.Abort() + return + } + + // Check if the Authorization header has the Bearer prefix + parts := strings.Split(authHeader, " ") + if len(parts) != 2 || parts[0] != "Bearer" { + c.JSON(http.StatusUnauthorized, gin.H{"error": "Authorization header format must be Bearer {token}"}) + c.Abort() + return + } + + // Extract the token + tokenString := parts[1] + + // Validate the token + userID, err := ValidateJWT(tokenString, cfg) + if err != nil { + c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid or expired token"}) + c.Abort() + return + } + + // Find the user in the database + var user models.User + if err := database.DB.First(&user, userID).Error; err != nil { + c.JSON(http.StatusUnauthorized, gin.H{"error": "User not found"}) + c.Abort() + return + } + + // Set user data in context + c.Set("userID", userID) + c.Set("user", user) + + c.Next() + } +} diff --git a/backend/internal/api/v1/loans/loans.go b/backend/internal/api/v1/loans/loans.go new file mode 100644 index 0000000..06d96b0 --- /dev/null +++ b/backend/internal/api/v1/loans/loans.go @@ -0,0 +1,248 @@ +package loans + +import ( + "net/http" + "strconv" + "time" + + "finance/backend/internal/database" + "finance/backend/internal/models" + + "github.com/gin-gonic/gin" + "gorm.io/gorm" +) + +// GetLoans returns all loans for the authenticated user +func GetLoans() gin.HandlerFunc { + return func(c *gin.Context) { + // Get user from context (set by auth middleware) + user, exists := c.Get("user") + if !exists { + c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"}) + return + } + + userObj := user.(*models.User) + var loans []models.Loan + + // Fetch all loans for the user + if err := database.DB.Where("user_id = ?", userObj.ID).Find(&loans).Error; err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to fetch loans"}) + return + } + + c.JSON(http.StatusOK, gin.H{"loans": loans}) + } +} + +// GetLoanByID returns a specific loan by ID +func GetLoanByID() gin.HandlerFunc { + return func(c *gin.Context) { + // Get user from context (set by auth middleware) + user, exists := c.Get("user") + if !exists { + c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"}) + return + } + userObj := user.(*models.User) + + // Get loan ID from URL parameter + loanID, err := strconv.ParseUint(c.Param("id"), 10, 32) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid loan ID format"}) + return + } + + var loan models.Loan + + // Fetch the loan and ensure it belongs to the authenticated user + if err := database.DB.Where("id = ? AND user_id = ?", loanID, userObj.ID).First(&loan).Error; err != nil { + if err == gorm.ErrRecordNotFound { + c.JSON(http.StatusNotFound, gin.H{"error": "Loan not found"}) + } else { + c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to fetch loan"}) + } + return + } + + c.JSON(http.StatusOK, gin.H{"loan": loan}) + } +} + +// CreateLoan creates a new loan +func CreateLoan() gin.HandlerFunc { + return func(c *gin.Context) { + // Get user from context (set by auth middleware) + user, exists := c.Get("user") + if !exists { + c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"}) + return + } + userObj := user.(*models.User) + + // Define a struct to bind the request JSON + var input struct { + Name string `json:"name" binding:"required"` + OriginalAmount int64 `json:"originalAmount" binding:"required"` + CurrentBalance int64 `json:"currentBalance" binding:"required"` + InterestRate float64 `json:"interestRate"` + StartDate string `json:"startDate" binding:"required"` + EndDate string `json:"endDate" binding:"required"` + AccountID *uint `json:"accountId"` + } + + // Bind JSON to struct + if err := c.ShouldBindJSON(&input); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + return + } + + // Parse dates + startDate, err := time.Parse("2006-01-02", input.StartDate) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid start date format"}) + return + } + + endDate, err := time.Parse("2006-01-02", input.EndDate) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid end date format"}) + return + } + + // Create loan object + loan := models.Loan{ + UserID: userObj.ID, + Name: input.Name, + OriginalAmount: input.OriginalAmount, + CurrentBalance: input.CurrentBalance, + InterestRate: input.InterestRate, + StartDate: startDate, + EndDate: endDate, + AccountID: input.AccountID, + } + + // Save to database + if err := database.DB.Create(&loan).Error; err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to create loan"}) + return + } + + c.JSON(http.StatusCreated, gin.H{"loan": loan}) + } +} + +// UpdateLoan updates an existing loan +func UpdateLoan() gin.HandlerFunc { + return func(c *gin.Context) { + // Get user from context (set by auth middleware) + user, exists := c.Get("user") + if !exists { + c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"}) + return + } + userObj := user.(*models.User) + + // Get loan ID from URL parameter + loanID, err := strconv.ParseUint(c.Param("id"), 10, 32) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid loan ID format"}) + return + } + + // Check if the loan exists and belongs to the user + var loan models.Loan + if err := database.DB.Where("id = ? AND user_id = ?", loanID, userObj.ID).First(&loan).Error; err != nil { + if err == gorm.ErrRecordNotFound { + c.JSON(http.StatusNotFound, gin.H{"error": "Loan not found"}) + } else { + c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to fetch loan"}) + } + return + } + + // Define a struct to bind the request JSON + var input struct { + Name string `json:"name"` + CurrentBalance int64 `json:"currentBalance"` + InterestRate float64 `json:"interestRate"` + EndDate string `json:"endDate"` + AccountID *uint `json:"accountId"` + } + + // Bind JSON to struct + if err := c.ShouldBindJSON(&input); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + return + } + + // Update fields if provided + if input.Name != "" { + loan.Name = input.Name + } + if input.CurrentBalance != 0 { + loan.CurrentBalance = input.CurrentBalance + } + if input.InterestRate != 0 { + loan.InterestRate = input.InterestRate + } + if input.EndDate != "" { + endDate, err := time.Parse("2006-01-02", input.EndDate) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid end date format"}) + return + } + loan.EndDate = endDate + } + if input.AccountID != nil { + loan.AccountID = input.AccountID + } + + // Save updates to database + if err := database.DB.Save(&loan).Error; err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to update loan"}) + return + } + + c.JSON(http.StatusOK, gin.H{"loan": loan}) + } +} + +// DeleteLoan deletes a loan +func DeleteLoan() gin.HandlerFunc { + return func(c *gin.Context) { + // Get user from context (set by auth middleware) + user, exists := c.Get("user") + if !exists { + c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"}) + return + } + userObj := user.(*models.User) + + // Get loan ID from URL parameter + loanID, err := strconv.ParseUint(c.Param("id"), 10, 32) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid loan ID format"}) + return + } + + // Check if the loan exists and belongs to the user + var loan models.Loan + if err := database.DB.Where("id = ? AND user_id = ?", loanID, userObj.ID).First(&loan).Error; err != nil { + if err == gorm.ErrRecordNotFound { + c.JSON(http.StatusNotFound, gin.H{"error": "Loan not found"}) + } else { + c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to fetch loan"}) + } + return + } + + // Delete the loan + if err := database.DB.Delete(&loan).Error; err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to delete loan"}) + return + } + + c.JSON(http.StatusOK, gin.H{"message": "Loan deleted successfully"}) + } +} diff --git a/backend/internal/api/v1/users/handler.go b/backend/internal/api/v1/users/handler.go new file mode 100644 index 0000000..9e53147 --- /dev/null +++ b/backend/internal/api/v1/users/handler.go @@ -0,0 +1,19 @@ +package users + +import ( + "net/http" + + "github.com/gin-gonic/gin" +) + +// GetCurrentUser returns the authenticated user's information +func GetCurrentUser(c *gin.Context) { + // Get user from context (set by auth middleware) + user, exists := c.Get("user") + if !exists { + c.JSON(http.StatusNotFound, gin.H{"error": "User not found"}) + return + } + + c.JSON(http.StatusOK, gin.H{"user": user}) +} diff --git a/backend/internal/config/config.go b/backend/internal/config/config.go new file mode 100644 index 0000000..f61f423 --- /dev/null +++ b/backend/internal/config/config.go @@ -0,0 +1,54 @@ +package config + +import ( + "log" + "os" + + "github.com/joho/godotenv" +) + +// Config holds the application configuration +type Config struct { + DatabaseDSN string + JWTSecret string // Secret key for signing JWTs + // Add other config fields here later (e.g., server port) +} + +// LoadConfig loads configuration from environment variables or a .env file +func LoadConfig() (*Config, error) { + // Attempt to load .env file (useful for development) + // In production, rely on environment variables set directly + err := godotenv.Load() // Load .env file from current directory or parent dirs + if err != nil { + log.Println("No .env file found, relying on environment variables") + } + + dsn := os.Getenv("DATABASE_DSN") + if dsn == "" { + // Set a default for local development if not provided + log.Println("DATABASE_DSN not set, using default local PostgreSQL DSN") + log.Println("IMPORTANT: Ensure PostgreSQL is running with the correct credentials.") + log.Println("Try creating a database 'finance' and setting up a user with the correct permissions.") + log.Println("Example commands:") + log.Println(" createdb finance") + log.Println(" createuser -P -s -e user_name") + + // Use more common/generic default credentials + dsn = "host=localhost user=postgres password=postgres dbname=finance port=5432 sslmode=disable TimeZone=UTC" + // Consider making the default conditional or removing it for stricter environments + } + + jwtSecret := os.Getenv("JWT_SECRET") + if jwtSecret == "" { + log.Println("WARNING: JWT_SECRET environment variable not set. Using an insecure default.") + // !!! IMPORTANT: Use a strong, randomly generated secret in production !!! + // For development only: + jwtSecret = "insecure-default-dev-secret-change-me" + // return nil, errors.New("JWT_SECRET environment variable is required") + } + + return &Config{ + DatabaseDSN: dsn, + JWTSecret: jwtSecret, + }, nil +} diff --git a/backend/internal/database/database.go b/backend/internal/database/database.go new file mode 100644 index 0000000..15228e2 --- /dev/null +++ b/backend/internal/database/database.go @@ -0,0 +1,61 @@ +package database + +import ( + "log" + "time" + + "finance/backend/internal/config" + "finance/backend/internal/models" + + "gorm.io/driver/postgres" + "gorm.io/gorm" + "gorm.io/gorm/logger" +) + +var DB *gorm.DB + +// InitDatabase initializes the database connection and runs migrations. +func InitDatabase(cfg *config.Config) error { + var err error + log.Println("Connecting to database...") + + // Configure GORM logger + // You might want to adjust the log level based on environment (e.g., Silent in production) + newLogger := logger.New( + log.New(log.Writer(), "\r\n", log.LstdFlags), // io writer + logger.Config{ + SlowThreshold: 200 * time.Millisecond, // Explicitly set slow query threshold + LogLevel: logger.Info, // Log all SQL + IgnoreRecordNotFoundError: true, + Colorful: false, // Disable color in logs, or true if terminal supports + }, + ) + + DB, err = gorm.Open(postgres.Open(cfg.DatabaseDSN), &gorm.Config{ + Logger: newLogger, + }) + + if err != nil { + log.Printf("Failed to connect to database: %v\n", err) + return err + } + + log.Println("Database connection established.") + + // Run Migrations + log.Println("Running database migrations...") + err = DB.AutoMigrate( + &models.User{}, + &models.Account{}, + &models.Transaction{}, + &models.Loan{}, + &models.Goal{}, + ) + if err != nil { + log.Printf("Failed to run migrations: %v\n", err) + return err + } + + log.Println("Database migrations completed.") + return nil +} diff --git a/backend/internal/models/models.go b/backend/internal/models/models.go new file mode 100644 index 0000000..c984012 --- /dev/null +++ b/backend/internal/models/models.go @@ -0,0 +1,97 @@ +package models + +import ( + "time" + + "golang.org/x/crypto/bcrypt" + "gorm.io/gorm" +) + +// User represents a user in the system +// We'll store a hashed password, not the plaintext one. +type User struct { + gorm.Model // Includes ID, CreatedAt, UpdatedAt, DeletedAt + Name string `gorm:"not null"` + Email string `gorm:"uniqueIndex;not null"` // Unique email + PasswordHash string `gorm:"not null"` // Store hashed password +} + +// SetPassword hashes the given password and sets it on the user model. +func (u *User) SetPassword(password string) error { + hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost) + if err != nil { + return err + } + u.PasswordHash = string(hashedPassword) + return nil +} + +// CheckPassword compares a given password with the user's hashed password. +// Returns nil if the password is correct, otherwise returns an error. +func (u *User) CheckPassword(password string) error { + return bcrypt.CompareHashAndPassword([]byte(u.PasswordHash), []byte(password)) +} + +// Account represents a financial account (e.g., bank account, credit card, cash) +// It belongs to a User. +type Account struct { + gorm.Model + UserID uint `gorm:"not null;index"` // Foreign key to User + User User // Belongs To relationship + Name string `gorm:"not null"` + Type string `gorm:"not null;index"` // e.g., "Bank", "Credit Card", "Cash", "Loan", "Income Source" + // Balance is stored in the smallest currency unit (e.g., cents) + // to avoid floating point issues. + Balance int64 `gorm:"not null;default:0"` +} + +// Transaction represents an income or expense event. +// It belongs to a User and is usually associated with an Account. +type Transaction struct { + gorm.Model + UserID uint `gorm:"not null;index"` // Foreign key to User + User User // Belongs To relationship + AccountID *uint `gorm:"index"` // Foreign key to Account (nullable, e.g., for cash transactions not tied to a bank) + Account *Account // Belongs To relationship (pointer for nullable FK) + Description string `gorm:"not null"` + // Amount stored in the smallest currency unit (e.g., cents) + Amount int64 `gorm:"not null"` + Type string `gorm:"not null;index"` // "Income" or "Expense" + Date time.Time `gorm:"not null;index"` // Date of the transaction + Category string `gorm:"index"` // e.g., "Salary", "Groceries", "Utilities" +} + +// Loan represents a loan taken by the user. +// It belongs to a User and may be linked to an Account representing the loan source/payments. +type Loan struct { + gorm.Model + UserID uint `gorm:"not null;index"` // Foreign key to User + User User // Belongs To relationship + AccountID *uint `gorm:"index"` // Optional FK to the related Account (e.g., where payments are made from/to) + Account *Account // Belongs To relationship + Name string `gorm:"not null"` // e.g., "Car Loan", "Student Loan" + OriginalAmount int64 `gorm:"not null"` // In smallest currency unit + CurrentBalance int64 `gorm:"not null"` // In smallest currency unit + InterestRate float64 // Annual interest rate (e.g., 0.05 for 5%) + StartDate time.Time + EndDate time.Time // Expected payoff date + // Add fields for payment frequency, next due date etc. if needed later +} + +// Goal represents a financial goal the user is working towards. +// It belongs to a User. +type Goal struct { + gorm.Model + UserID uint `gorm:"not null;index"` // Foreign key to User + User User // Belongs To relationship + Name string `gorm:"not null"` // e.g., "Save for Down Payment", "Pay Off Credit Card" + TargetAmount int64 `gorm:"not null"` // In smallest currency unit + CurrentAmount int64 `gorm:"not null;default:0"` // In smallest currency unit + TargetDate time.Time // Optional target date for the goal + Status string `gorm:"not null;default:'Active';index"` // e.g., "Active", "Achieved", "Cancelled" + // Link to specific accounts or loans if needed (e.g., goal to pay off a specific loan) + // RelatedAccountID *uint + // RelatedLoanID *uint +} + +// Add other models below (Goal) diff --git a/backend/internal/router/router.go b/backend/internal/router/router.go new file mode 100644 index 0000000..b82e1af --- /dev/null +++ b/backend/internal/router/router.go @@ -0,0 +1,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 +} |