Skip to content

Commit

Permalink
refactor: add middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
Siumauricio committed Jan 4, 2025
1 parent feb49ab commit e41c222
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 8 deletions.
9 changes: 1 addition & 8 deletions apps/golang/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,42 +29,36 @@ func main() {
log.Fatal("METRICS_TOKEN and METRICS_URL_CALLBACK environment variables are required")
}

// Initialize database
db, err := database.InitDB()
if err != nil {
log.Fatal(err)
}

app := fiber.New()

// CORS configuration
app.Use(cors.New(cors.Config{
AllowOrigins: "*",
AllowHeaders: "Origin, Content-Type, Accept, Authorization",
}))

// Health check endpoint (no auth required)
app.Get("/health", func(c *fiber.Ctx) error {
return c.JSON(fiber.Map{
"status": "ok",
})
})

// Add auth middleware to all routes except /health
app.Use(func(c *fiber.Ctx) error {
if c.Path() == "/health" {
return c.Next()
}
return middleware.AuthMiddleware()(c)
})

// Get metrics endpoint (compatible with frontend)
app.Get("/metrics", func(c *fiber.Ctx) error {
limit := c.Query("limit", "50")

var metrics []monitoring.SystemMetrics
if limit == "all" {
// Get all metrics
dbMetrics, err := db.GetLastNMetrics(10000)
if err != nil {
return c.Status(500).JSON(fiber.Map{
Expand All @@ -75,10 +69,9 @@ func main() {
metrics = append(metrics, monitoring.ConvertToSystemMetrics(m))
}
} else {
// Get limited metrics
n, err := strconv.Atoi(limit)
if err != nil {
n = 50 // default value
n = 50
}
dbMetrics, err := db.GetLastNMetrics(n)
if err != nil {
Expand Down
42 changes: 42 additions & 0 deletions apps/golang/middleware/auth.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package middleware

import (
"os"
"strings"

"github.com/gofiber/fiber/v2"
)

func AuthMiddleware() fiber.Handler {
return func(c *fiber.Ctx) error {
expectedToken := os.Getenv("METRICS_TOKEN")
if expectedToken == "" {
return c.Next()
}

authHeader := c.Get("Authorization")
if authHeader == "" {
return c.Status(401).JSON(fiber.Map{
"error": "Authorization header is required",
})
}

// Check if the header starts with "Bearer "
if !strings.HasPrefix(authHeader, "Bearer ") {
return c.Status(401).JSON(fiber.Map{
"error": "Invalid authorization format. Use 'Bearer TOKEN'",
})
}

// Extract the token
token := strings.TrimPrefix(authHeader, "Bearer ")

if token != expectedToken {
return c.Status(401).JSON(fiber.Map{
"error": "Invalid token",
})
}

return c.Next()
}
}

0 comments on commit e41c222

Please sign in to comment.