2023-09-15 13:14:43 -04:00
|
|
|
/*
|
|
|
|
Copyright © 2023 AGECEM & Victor Lacasse-Beaudoin
|
|
|
|
*/
|
|
|
|
package cmd
|
|
|
|
|
|
|
|
import (
|
2023-09-19 16:47:57 -04:00
|
|
|
"crypto/subtle"
|
2023-09-15 13:14:43 -04:00
|
|
|
"fmt"
|
2023-09-15 16:15:32 -04:00
|
|
|
"log"
|
2024-02-14 16:53:59 -05:00
|
|
|
"net/http"
|
2023-09-15 13:14:43 -04:00
|
|
|
|
2023-09-15 18:13:48 -04:00
|
|
|
"git.agecem.com/agecem/bottin-ag/apihandler"
|
2023-09-15 16:15:32 -04:00
|
|
|
"git.agecem.com/agecem/bottin-ag/config"
|
2023-09-16 17:22:12 -04:00
|
|
|
"git.agecem.com/agecem/bottin-ag/dbclient"
|
2024-02-14 16:48:20 -05:00
|
|
|
bottindata "git.agecem.com/agecem/bottin/v6/data"
|
2023-09-15 16:36:56 -04:00
|
|
|
"github.com/labstack/echo/v4"
|
|
|
|
"github.com/labstack/echo/v4/middleware"
|
2023-09-15 13:14:43 -04:00
|
|
|
"github.com/spf13/cobra"
|
|
|
|
)
|
|
|
|
|
|
|
|
// apiCmd represents the api command
|
|
|
|
var apiCmd = &cobra.Command{
|
|
|
|
Use: "api",
|
|
|
|
Short: "Start the API server",
|
|
|
|
Run: func(cmd *cobra.Command, args []string) {
|
2023-09-15 17:10:57 -04:00
|
|
|
cfg, err := config.UnmarshalConfig()
|
2023-09-15 16:15:32 -04:00
|
|
|
if err != nil {
|
|
|
|
log.Fatal(err)
|
|
|
|
}
|
|
|
|
|
2023-09-15 16:36:56 -04:00
|
|
|
e := echo.New()
|
|
|
|
|
|
|
|
e.Pre(middleware.AddTrailingSlash())
|
|
|
|
|
2023-09-19 16:47:57 -04:00
|
|
|
if cfg.API.Key != "" {
|
|
|
|
e.Use(middleware.KeyAuth(func(key string, c echo.Context) (bool, error) {
|
|
|
|
return subtle.ConstantTimeCompare([]byte(key), []byte(cfg.API.Key)) == 1, nil
|
|
|
|
}))
|
|
|
|
log.Println("API server is using an API key")
|
|
|
|
}
|
|
|
|
|
2023-09-15 18:13:48 -04:00
|
|
|
v0 := e.Group("/v0")
|
|
|
|
|
2024-02-14 16:53:59 -05:00
|
|
|
httpClient := http.DefaultClient
|
|
|
|
|
|
|
|
bottinApiClient := bottindata.NewApiClient(
|
|
|
|
httpClient,
|
|
|
|
cfg.Bottin.API.Key,
|
|
|
|
cfg.Bottin.API.Host,
|
|
|
|
cfg.Bottin.API.Protocol,
|
|
|
|
cfg.Bottin.API.Port,
|
|
|
|
)
|
2023-09-15 18:13:48 -04:00
|
|
|
|
2023-09-16 18:40:18 -04:00
|
|
|
dbClient, err := dbclient.New(cfg.DB.Host, cfg.DB.Database, cfg.DB.User, cfg.DB.Password, cfg.DB.Port, cfg.DB.UseSSL)
|
2023-09-16 17:22:12 -04:00
|
|
|
if err != nil {
|
|
|
|
log.Fatal(err)
|
|
|
|
}
|
2023-09-19 16:47:57 -04:00
|
|
|
defer dbClient.DB.Close()
|
2023-09-16 17:22:12 -04:00
|
|
|
|
2023-09-16 17:44:38 -04:00
|
|
|
handler := apihandler.New(bottinApiClient, dbClient)
|
2023-09-16 17:22:12 -04:00
|
|
|
|
|
|
|
if err := handler.DBClient.CreateTablesIfNotExist(); err != nil {
|
|
|
|
log.Fatal(err)
|
|
|
|
}
|
|
|
|
|
2023-09-16 15:05:13 -04:00
|
|
|
apihandler.DeclareRoutes(v0, &handler)
|
2023-09-15 18:13:48 -04:00
|
|
|
|
2023-09-15 16:36:56 -04:00
|
|
|
e.Start(fmt.Sprintf(":%d", cfg.API.Port))
|
2023-09-15 13:14:43 -04:00
|
|
|
},
|
|
|
|
}
|
|
|
|
|
|
|
|
func init() {
|
|
|
|
rootCmd.AddCommand(apiCmd)
|
|
|
|
}
|