agecem-org/cmd/server.go
Victor Lacasse-Beaudoin 3bab5b3b51 Refactor api_handlers et web_handlers
serverhandlers -> api_handlers
html handlers dans cmd/server -> web_handlers
2023-08-20 16:19:05 -04:00

253 lines
8.8 KiB
Go

/*
Copyright © 2023 AGECEM
*/
package cmd
import (
"crypto/subtle"
"fmt"
"log"
"embed"
"html/template"
"io"
"net/http"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"git.agecem.com/agecem/agecem-org/api_handlers"
"git.agecem.com/agecem/agecem-org/config"
"git.agecem.com/agecem/agecem-org/media"
"git.agecem.com/agecem/agecem-org/public"
"git.agecem.com/agecem/agecem-org/templates"
"git.agecem.com/agecem/agecem-org/web_handlers"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
)
type Template struct {
templates *template.Template
}
var cfg config.Config
var (
publicFS embed.FS
templatesFS embed.FS
)
// serverCmd represents the server command
var serverCmd = &cobra.Command{
Use: "server",
Short: "Démarrer le serveur web",
Run: func(cmd *cobra.Command, args []string) {
if err := viper.Unmarshal(&cfg); err != nil {
log.Fatal(err)
}
mediaClient, err := media.NewMediaClientFromViper()
if err != nil {
log.Fatal(err)
}
new_buckets, err := mediaClient.Seed()
if err != nil {
log.Fatal(err)
}
log.Printf("Seeded %d buckets.\n", len(new_buckets))
RunServer()
},
}
func init() {
rootCmd.AddCommand(serverCmd)
publicFS = public.GetPublicFS()
templatesFS = templates.GetTemplatesFS()
// server.port - --server-port
serverCmd.Flags().Int("server-port", 8080, "Port to run the webserver on (config: server.port)")
viper.BindPFlag("server.port", serverCmd.Flags().Lookup("server-port"))
// Not currently used
/*
// server.documents.location - --server-documents-location
serverCmd.Flags().String("server-documents-location", "us-east", "Storage bucket location (config: server.documents.location)")
viper.BindPFlag("server.documents.location", serverCmd.Flags().Lookup("server-documents-location"))
*/
// server.documents.endpoint - --server-documents-endpoint
serverCmd.Flags().String("server-documents-endpoint", "minio:9000", "Storage server endpoint (config: server.documents.endpoint)")
viper.BindPFlag("server.documents.endpoint", serverCmd.Flags().Lookup("server-documents-endpoint"))
// server.documents.access_key_id - --server-documents-access-key-id
serverCmd.Flags().String("server-documents-access-key-id", "agecem-org", "Storage server access key id (config: server.documents.access_key_id)")
viper.BindPFlag("server.documents.access_key_id", serverCmd.Flags().Lookup("server-documents-access-key-id"))
// server.documents.secret_access_key - --server-documents-secret-access-key
serverCmd.Flags().String("server-documents-secret-access-key", "agecem-org", "Storage server secret access key (config: server.documents.secret_access_key)")
viper.BindPFlag("server.documents.secret_access_key", serverCmd.Flags().Lookup("server-documents-secret-access-key"))
// server.documents.use_ssl - --server-documents-use-ssl
serverCmd.Flags().Bool("server-documents-use-ssl", false, "Storage server SSL status (config: server.documents.use_ssl)")
viper.BindPFlag("server.documents.use_ssl", serverCmd.Flags().Lookup("server-documents-use-ssl"))
// server.documents.buckets - --server-documents-buckets
serverCmd.Flags().StringToString("server-documents-buckets", map[string]string{
"proces-verbaux": "Procès-verbaux",
"politiques": "Politiques",
"reglements": "Règlements",
"formulaires": "Formulaires",
}, "Buckets that are allowed to be accessed by the API (config: server.documents.buckets)")
viper.BindPFlag("server.documents.buckets", serverCmd.Flags().Lookup("server-documents-buckets"))
// server.api.auth - --server-api-auth
serverCmd.Flags().Bool("server-api-auth", true, "Enable to allow key authentication for /v1 routes (config: server.api.auth)")
viper.BindPFlag("server.api.auth", serverCmd.Flags().Lookup("server-api-auth"))
// server.api.key - --server-api-key
serverCmd.Flags().String("server-api-key", "agecem-org", "Key to use for authenticating to /v1 routes")
viper.BindPFlag("server.api.key", serverCmd.Flags().Lookup("server-api-key"))
// server.api.port
serverCmd.Flags().Int("server-api-port", 8080, "API server port (config: server.api.port)")
viper.BindPFlag("server.api.port", serverCmd.Flags().Lookup("server-api-port"))
// server.api.protocol
serverCmd.Flags().String("server-api-protocol", "http", "API server protocol (http/https) (config: server.api.protocol)")
viper.BindPFlag("server.api.protocol", serverCmd.Flags().Lookup("server-api-protocol"))
// server.api.host
serverCmd.Flags().String("server-api-host", "localhost", "API server host (config: server.api.host)")
viper.BindPFlag("server.api.host", serverCmd.Flags().Lookup("server-api-host"))
// server.admin.auth - --server-admin-auth
serverCmd.Flags().Bool("server-admin-auth", true, "Enable to allow basic authentication for /admin routes (config: server.admin.auth)")
viper.BindPFlag("server.admin.auth", serverCmd.Flags().Lookup("server-admin-auth"))
// server.admin.username - --server-admin-username
serverCmd.Flags().String("server-admin-username", "agecem-org", "Username for basic authentication for /admin routes (config: server.admin.username)")
viper.BindPFlag("server.admin.username", serverCmd.Flags().Lookup("server-admin-username"))
// server.admin.password - --server-admin-password
serverCmd.Flags().String("server-admin-password", "agecem-org", "Password for basic authentication for /admin routes (config: server.admin.password)")
viper.BindPFlag("server.admin.password", serverCmd.Flags().Lookup("server-admin-password"))
}
func RunServer() {
e := echo.New()
t := &Template{
templates: template.Must(template.ParseFS(templatesFS, "html/*.gohtml")),
}
e.Renderer = t
e.Pre(middleware.RemoveTrailingSlash())
groupStatic := e.Group("/public/*")
groupStatic.Use(middleware.StaticWithConfig(middleware.StaticConfig{
Root: "/",
Filesystem: http.FS(publicFS),
//TODO
//Browse: true,
}))
groupV1 := e.Group("/v1")
groupV1.Use(middleware.AddTrailingSlash())
if cfg.Server.Api.Auth {
if len(cfg.Server.Api.Key) < 10 {
log.Fatal("server.api.auth is enabled, but server.api.key is too small (needs at least 10 characters)")
}
groupV1.Use(middleware.KeyAuth(func(key string, c echo.Context) (bool, error) {
return subtle.ConstantTimeCompare([]byte(key), []byte(cfg.Server.Api.Key)) == 1, nil
}))
log.Println("Key auth for /v1 activated")
}
groupAdmin := e.Group("/admin")
groupAdmin.Use(middleware.AddTrailingSlash())
if cfg.Server.Admin.Auth {
if len(cfg.Server.Admin.Username) < 5 {
log.Fatal("server.admin.auth is enabled, but server.admin.username is too small (needs at least 5 characters)")
}
if len(cfg.Server.Admin.Password) < 10 {
log.Fatal("server.admin.auth is enabled, but server.admin.password is too small (needs at least 10 characters)")
}
groupAdmin.Use(middleware.BasicAuth(func(username_entered, password_entered string, c echo.Context) (bool, error) {
// Be careful to use constant time comparison to prevent timing attacks
if subtle.ConstantTimeCompare([]byte(username_entered), []byte(cfg.Server.Admin.Username)) == 1 &&
subtle.ConstantTimeCompare([]byte(password_entered), []byte(cfg.Server.Admin.Password)) == 1 {
return true, nil
}
return false, nil
}))
log.Println("Basic auth for /admin activated")
}
// API Routes
groupV1.GET("", api_handlers.HandleV1)
groupV1.POST("/seed", api_handlers.HandleV1Seed)
groupV1.GET("/bucket", api_handlers.HandleV1BucketList)
groupV1.GET("/bucket/:bucket", api_handlers.HandleV1BucketRead)
groupV1.POST("/bucket/:bucket", api_handlers.HandleV1DocumentCreate)
groupV1.GET("/bucket/:bucket/:document", api_handlers.HandleV1DocumentRead)
groupV1.PUT("/bucket/:bucket/:document", api_handlers.HandleV1DocumentUpdate)
groupV1.DELETE("/bucket/:bucket/:document", api_handlers.HandleV1DocumentDelete)
// HTML Routes
e.GET("/", web_handlers.HandleIndex)
//e.GET("/a-propos", web_handlers.HandleAPropos)
//e.GET("/actualite", web_handlers.HandleActualite)
//e.GET("/actualite/:article", web_handlers.HandleActualiteArticle)
e.GET("/vie-etudiante", web_handlers.HandleVieEtudiante)
e.GET("/vie-etudiante/:organisme", web_handlers.HandleVieEtudianteOrganisme)
e.GET("/documentation", web_handlers.HandleDocumentation)
e.GET("/formulaires", web_handlers.HandleFormulaires)
// Public Routes
e.GET("/public/documentation/:bucket/:document", web_handlers.HandlePublicDocumentation)
// Admin Routes
groupAdmin.GET("", web_handlers.HandleAdmin)
groupAdmin.GET("/documents/upload", web_handlers.HandleAdminDocumentsUpload)
groupAdmin.POST("/documents/upload", web_handlers.HandleAdminDocumentsUploadPOST)
e.Logger.Fatal(e.Start(
fmt.Sprintf(":%d", cfg.Server.Port)))
}
func (t *Template) Render(w io.Writer, name string, data interface{}, c echo.Context) error {
return t.templates.ExecuteTemplate(w, name, data)
}