package routers import ( "context" "fmt" "log" "net/http" "strconv" "git.paulbsd.com/paulbsd/ipbl/src/config" "git.paulbsd.com/paulbsd/ipbl/src/models" "github.com/labstack/echo/v4" ) // RegisterRoutes runs the main echo HTTP server func RegisterRoutes(e *echo.Echo, ctx *context.Context, cfg *config.Config) { e.GET("/", func(c echo.Context) error { return c.HTML(http.StatusOK, `

Welcome to ipbl software (https://git.paulbsd.com/paulbsd/ipbl)

`) }) e.GET("/ip/:ip", func(c echo.Context) (err error) { ret, err := models.GetIP(ctx, cfg, c.Param("ip")) return Result(c, err, ret) }) e.POST("/ip", func(c echo.Context) (err error) { var ip = new(models.IP) var msg string err = c.Bind(ip) if err != nil { return Result(c, fmt.Errorf("error when parsing body"), "") } num, err := ip.InsertIP(cfg) fmt.Println(err) if err != nil { return Result(c, err, "") } if num > 0 { msg = fmt.Sprintf("Inserted %d IP", num) } else { msg = "No IP inserted" } return Result(c, err, msg) }) e.GET("/ips", func(c echo.Context) (err error) { limit := 50 if c.QueryParam("limit") != "" { limit, _ = strconv.Atoi(c.QueryParam("limit")) } ret, err := models.GetIPs(ctx, cfg, limit) return Result(c, err, ret) }) // retro-compat e.GET("/ips/lastday", func(c echo.Context) (err error) { interval := "1 day" ret, err := models.GetIPsLast(ctx, cfg, interval) return Result(c, err, ret) }) e.GET("/ips/last", func(c echo.Context) (err error) { interval := "10 minutes" ret, err := models.GetIPsLast(ctx, cfg, interval) return Result(c, err, ret) }) e.POST("/ips", func(c echo.Context) (err error) { var ips = []models.IP{} var msg string err = c.Bind(&ips) if err != nil { return Result(c, err, ips) } numinsert, numupdate, _, _ := models.InsertIPBulk(cfg, &ips) if numinsert > 0 { msg = fmt.Sprintf("Inserted %d IP", numinsert) log.Println(msg) } if numupdate > 0 { msg = fmt.Sprintf("Updated %d IP", numupdate) log.Println(msg) } return Result(c, err, msg) }) e.GET("/ips/whitelist", func(c echo.Context) (err error) { whitelists, err := models.GetWhitelists(*cfg) return Result(c, err, whitelists) }) e.POST("/ips/whitelist", func(c echo.Context) (err error) { var cidr models.Whitelist err = c.Bind(&cidr) if err == nil && cidr.Verify() { err = cidr.InsertOrUpdate(*cfg) return Result(c, err, cidr) } return Result(c, err, nil) }) e.DELETE("/ips/whitelist/:ip", func(c echo.Context) (err error) { var ip = c.Param("ip") var cidr models.Whitelist err = cidr.Delete(*cfg, ip) if err != nil { return c.JSON(http.StatusOK, "Deleted old CIDR") } return }) e.Logger.Fatal( e.Start( fmt.Sprintf(":%d", cfg.Switchs.Port))) }