package middleware import ( "log/slog" "net/http" "orbits-server/internal/server/api/assets" "strings" "time" "github.com/gin-gonic/gin" ) func SlogMiddleware(logger *slog.Logger) gin.HandlerFunc { // Make a slog-looking logger, inspired by the gin docs themself // JSON logger: https://gin-gonic.com/en/docs/logging/structured-logging/ return func(c *gin.Context) { start := time.Now() path := c.Request.URL.Path query := c.Request.URL.RawQuery c.Next() logger.Debug("request", slog.String("method", c.Request.Method), slog.String("path", path), slog.String("query", query), slog.Int("status", c.Writer.Status()), slog.Duration("latency", time.Since(start)), slog.String("client_ip", c.ClientIP()), slog.Int("body_size", c.Writer.Size()), ) if len(c.Errors) > 0 { for _, err := range c.Errors { logger.Error("request error", slog.String("error", err.Error())) } } } } func AuthMiddleware() gin.HandlerFunc { return func(c *gin.Context) { authorizationHeader := c.GetHeader("Authorization") if len(authorizationHeader) == 0 { c.AbortWithStatusJSON(http.StatusUnauthorized, assets.BasicResponse{ Msg: "Authorization header is required", }) return } headerParts := strings.Split(authorizationHeader, " ") // The header must be a specific format, 0 being the bearer text and 1 being the token itself, making it 2 pieces total // In the following if statement we verify both parts if the part after Bearer is empty its only 1 part for example if len(headerParts) != 2 || headerParts[0] != "Bearer" { c.AbortWithStatusJSON(http.StatusUnauthorized, assets.BasicResponse{ Msg: "Authorization header is invalid", }) return } //givenKey := headerParts[1] } }