prosody-password/internal/api/server.go

94 lines
2.2 KiB
Go
Raw Normal View History

2023-07-05 22:07:10 +02:00
package api
import (
2023-07-07 23:31:32 +02:00
"fmt"
2023-07-05 22:07:10 +02:00
"log"
"gitea.urkob.com/urko/prosody-password/internal/api/handler"
2023-07-07 23:31:32 +02:00
"gitea.urkob.com/urko/prosody-password/internal/services/fail2ban"
2023-07-05 22:07:10 +02:00
"gitea.urkob.com/urko/prosody-password/internal/services/prosody"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/cors"
"github.com/gofiber/template/handlebars/v2"
)
type RestServer struct {
app *fiber.App
prosodyService *prosody.Prosody
2023-07-07 23:31:32 +02:00
fail2banSrv *fail2ban.Fail2Ban
2023-07-05 22:07:10 +02:00
}
func NewRestServer(
prosodyService *prosody.Prosody,
2023-07-07 23:31:32 +02:00
fail2banSrv *fail2ban.Fail2Ban,
2023-07-05 22:07:10 +02:00
) *RestServer {
return &RestServer{
prosodyService: prosodyService,
2023-07-07 23:31:32 +02:00
fail2banSrv: fail2banSrv,
2023-07-05 22:07:10 +02:00
}
}
func (s *RestServer) Start(apiPort, views string) error {
engine := handlebars.New(views, ".hbs")
s.app = fiber.New(fiber.Config{
Views: engine,
})
// Or extend your config for customization
s.app.Use(cors.New(cors.Config{
AllowMethods: "POST,OPTIONS",
AllowOrigins: "*",
AllowHeaders: "Origin, Accept, Content-Type, X-CSRF-Token, Authorization",
ExposeHeaders: "Origin",
}))
s.loadViews()
2023-07-07 23:31:32 +02:00
prosodyHdl := handler.NewProsodyHandler(s.prosodyService, s.fail2banSrv)
2023-07-05 22:07:10 +02:00
s.app.Post("/changePassword", func(c *fiber.Ctx) error {
2023-07-07 23:41:51 +02:00
log.Println("c.IPs()", c.IPs())
log.Println("c.IP", c.IP())
2023-07-07 23:31:32 +02:00
for _, ip := range c.IPs() {
if !s.fail2banSrv.CanChangePassword(ip) {
return handler.RenderError(c, fmt.Errorf("id is empty"), "Too many tries, blocked for 1h")
}
}
2023-07-05 22:07:10 +02:00
return prosodyHdl.Post(c)
})
if err := s.app.Listen(":" + apiPort); err != nil {
log.Fatalln("app.Listen:", err)
return err
}
return nil
}
func (s *RestServer) loadViews() {
s.app.Get("/", func(c *fiber.Ctx) error {
return c.Render("index", fiber.Map{})
})
s.app.Get("/error", func(c *fiber.Ctx) error {
message := c.Query("message")
return renderError(c, nil, message)
})
}
func renderError(c *fiber.Ctx, err error, message string) error {
if err != nil {
log.Printf("renderError: %s\n", err)
}
return c.Render("error", fiber.Map{
"message": message,
})
}
func (s *RestServer) Shutdown() error {
if err := s.app.Server().Shutdown(); err != nil {
log.Printf("app.Server().Shutdown(): %s\n", err)
return err
}
return nil
}