agendas/server.go

78 lines
1.7 KiB
Go
Raw Permalink Normal View History

2024-12-23 20:57:58 -05:00
package main
import (
"context"
2024-12-30 18:10:31 -05:00
"crypto/subtle"
2024-12-23 20:57:58 -05:00
"fmt"
2024-12-30 18:10:31 -05:00
"log"
2024-12-23 20:57:58 -05:00
2024-12-30 15:00:42 -05:00
"git.agecem.com/bottin/agendas/ui"
2024-12-23 20:57:58 -05:00
"git.agecem.com/bottin/bottin/v10/pkg/bottin"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
)
2024-12-30 15:00:42 -05:00
func RunServer(ctx context.Context, cfg Config, bottinClient *bottin.APIClient, dbClient *DBClient) error {
2024-12-23 20:57:58 -05:00
select {
case <-ctx.Done():
return ctx.Err()
default:
if bottinClient == nil {
return fmt.Errorf("nil bottin client")
}
2024-12-30 15:00:42 -05:00
if dbClient == nil {
return fmt.Errorf("nil dbClient")
}
2024-12-30 19:13:05 -05:00
if err := dbClient.Init(ctx); err != nil {
return err
}
2024-12-23 20:57:58 -05:00
e := echo.New()
2024-12-30 18:10:31 -05:00
r := ui.NewRenderer()
if r == nil {
return fmt.Errorf("nil renderer")
}
e.Renderer = r
2024-12-23 20:57:58 -05:00
e.Pre(middleware.AddTrailingSlash())
2024-12-30 18:10:31 -05:00
// basic auth
if len(cfg.Credentials) == 0 {
return fmt.Errorf("UI requires at least one credential (config key `Credentials` of type map[string]string)")
}
2024-12-30 19:13:05 -05:00
e.Pre(middleware.BasicAuth(
2024-12-30 18:10:31 -05:00
func(username, password string, c echo.Context) (bool, error) {
for validUser, validPass := range cfg.Credentials {
userOK := subtle.ConstantTimeCompare([]byte(username), []byte(validUser)) == 1
passOK := subtle.ConstantTimeCompare([]byte(password), []byte(validPass)) == 1
if userOK && passOK {
// log successful basic auths username
log.Println("login ok for user", username)
return true, nil
}
}
return false, nil
}),
)
2024-12-30 15:00:42 -05:00
e.GET("/", UIIndex(ctx, bottinClient, dbClient))
//e.GET("/transaction/", UIReadTransaction
e.POST("/transaction/", UICreateTransaction(ctx, cfg, bottinClient, dbClient))
2024-12-23 20:57:58 -05:00
2024-12-30 17:30:37 -05:00
address := fmt.Sprintf(":%d", cfg.Port)
if cfg.TLS.Enabled {
return e.StartTLS(address, cfg.TLS.Cert, cfg.TLS.Key)
} else {
return e.Start(address)
}
2024-12-23 20:57:58 -05:00
}
}