Skip to content

Commit

Permalink
Add a custom middleware to check the list of trusted proxies
Browse files Browse the repository at this point in the history
  • Loading branch information
yunkon-kim committed Nov 23, 2023
1 parent 0bd09dc commit a745aa9
Showing 1 changed file with 23 additions and 6 deletions.
29 changes: 23 additions & 6 deletions websrc/serve/serve.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,13 @@ import (
"html/template"
"io"
"net/http"
"strings"

"github.com/cloud-barista/cm-data-mold/websrc/routes"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
)

// var router *gin.Engine

// TemplateRenderer is a custom html/template renderer for Echo framework
type TemplateRenderer struct {
templates *template.Template
Expand All @@ -29,6 +28,25 @@ func (t *TemplateRenderer) Render(w io.Writer, name string, data interface{}, c
return t.templates.ExecuteTemplate(w, name, data)
}

// Custom middleware to check the list of trusted proxies
func TrustedProxiesMiddleware(trustedProxies []string) echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
clientIP := c.RealIP() // Echo gets the real IP of the client

for _, proxy := range trustedProxies {
if strings.HasPrefix(clientIP, proxy) {
// Request is from a trusted proxy
return next(c)
}
}

// Handling requests from untrusted sources
return echo.NewHTTPError(http.StatusForbidden, "Access denied")
}
}
}

func InitServer() *echo.Echo {
// router = gin.New()
// router.Use(gin.Logger())
Expand All @@ -41,17 +59,15 @@ func InitServer() *echo.Echo {

// router.ForwardedByClientIP = true
// router.SetTrustedProxies([]string{"127.0.0.1"})

// help needed
e.Use(TrustedProxiesMiddleware([]string{"127.0.0.1"}))

// router.Static("/res", "./web")
// router.LoadHTMLGlob("./web/templates/*")
// router.StaticFile("/favicon.ico", "./web/assets/favicon.ico")

e.Static("/res", "./web")
e.File("/favicon.ico", "./web/assets/favicon.ico")
renderer := &TemplateRenderer{
templates: template.Must(template.ParseGlob("*.html")),
templates: template.Must(template.ParseGlob("./web/templates/*.html")),
}
e.Renderer = renderer

Expand All @@ -78,6 +94,7 @@ func Run(rt *echo.Echo, port string) {
// rt.Run(":" + port)
port = fmt.Sprintf(":%s", port)
if err := rt.Start(port); err != nil && err != http.ErrServerClosed {
rt.Logger.Error(err)
rt.Logger.Panic("shuttig down the server")
}
}
Expand Down

0 comments on commit a745aa9

Please sign in to comment.