-
-
Notifications
You must be signed in to change notification settings - Fork 568
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
feb49ab
commit e41c222
Showing
2 changed files
with
43 additions
and
8 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | ||
} | ||
} |