agecem-org/cmd/server.go

422 lines
13 KiB
Go

/*
Copyright © 2023 AGECEM
*/
package cmd
import (
"context"
"crypto/subtle"
"fmt"
"log"
"embed"
"html/template"
"io"
"net/http"
"sort"
"github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/credentials"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"git.agecem.com/agecem/agecem-org/public"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
)
type Template struct {
templates *template.Template
}
var embedFS 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) {
RunServer()
},
}
func init() {
rootCmd.AddCommand(serverCmd)
embedFS = public.GetEmbedFS()
// 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"))
// 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", "", "Storage server access key id (config: server.documents.access_key_id)")
viper.BindPFlag("documents.accessKeyID", serverCmd.Flags().Lookup("documents-access-key-id"))
// server.documents.secret_access_key - --server-documents-secret-access-key
serverCmd.Flags().String("server-documents-secret-access-key", "", "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", true, "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().StringSlice("server-documents-buckets", nil, "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", false, "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", "", "Key to use for authenticating to /v1 routes")
viper.BindPFlag("server.api.key", serverCmd.Flags().Lookup("server-api-key"))
}
func RunServer() {
e := echo.New()
t := &Template{
templates: template.Must(template.ParseFS(embedFS, "html/*.gohtml")),
}
e.Renderer = t
e.Pre(middleware.RemoveTrailingSlash())
groupV1 := e.Group("/v1")
groupV1.Use(middleware.AddTrailingSlash())
if viper.GetBool("server.api.auth") {
if len(viper.GetString("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(viper.GetString("server.api.key"))) == 1, nil
}))
}
// API Routes
groupV1.GET("", handleV1)
groupV1.POST("/seed", handleV1Seed)
groupV1.GET("/bucket", handleV1BucketList)
groupV1.GET("/bucket/:bucket", handleV1BucketRead)
groupV1.POST("/bucket/:bucket", handleV1DocumentCreate)
groupV1.GET("/bucket/:bucket/:document", handleV1DocumentRead)
groupV1.PUT("/bucket/:bucket/:document", handleV1DocumentUpdate)
groupV1.DELETE("/bucket/:bucket/:document", handleV1DocumentDelete)
// Static Routes
e.GET("/static/general.css", handleStaticCSSGeneral)
e.GET("/static/index.css", handleStaticCSSIndex)
// HTML Routes
e.GET("/", handleIndex)
e.GET("/a-propos", handleAPropos)
e.GET("/actualite", handleActualite)
e.GET("/actualite/:article", handleActualiteArticle)
e.GET("/vie-etudiante", handleVieEtudiante)
e.GET("/vie-etudiante/:organisme", handleVieEtudianteOrganisme)
e.GET("/documentation", handleDocumentation)
e.GET("/formulaires", handleFormulaires)
e.Logger.Fatal(e.Start(
fmt.Sprintf(":%d", viper.GetInt("server.port"))))
}
func (t *Template) Render(w io.Writer, name string, data interface{}, c echo.Context) error {
return t.templates.ExecuteTemplate(w, name, data)
}
// API Handlers
// handleV1 affiche les routes accessibles.
// Les routes sont triées selon .Path, pour les rendre plus facilement navigables.
func handleV1(c echo.Context) error {
routes := c.Echo().Routes()
sort.Slice(routes, func(i, j int) bool { return routes[i].Path < routes[j].Path })
return c.JSON(http.StatusOK, routes)
}
// handleV1Seed créé des buckets dans minio selon la liste de buckets dans server.documents.buckets
// Les buckets sont créés avec paramètres par défaut, et sont ensuite visible dans /v1/bucket.
func handleV1Seed(c echo.Context) error {
documents_buckets := viper.GetStringSlice("server.documents.buckets")
documents_endpoint := viper.GetString("server.documents.endpoint")
documents_access_key_id := viper.GetString("server.documents.access_key_id")
documents_secret_access_key := viper.GetString("server.documents.secret_access_key")
documents_use_ssl := viper.GetBool("server.documents.use_ssl")
// Initialize minio client object
client, err := minio.New(documents_endpoint, &minio.Options{
Creds: credentials.NewStaticV4(documents_access_key_id, documents_secret_access_key, ""),
Secure: documents_use_ssl,
})
if err != nil {
return c.JSON(http.StatusInternalServerError, map[string]string{
"message": "Error during minio#New",
})
}
var new_buckets []string
for _, bucket := range documents_buckets {
exists, err := client.BucketExists(context.Background(), bucket)
if err != nil {
return c.JSON(http.StatusInternalServerError, map[string]string{
"message": "Error during minio#BucketExists",
})
}
if exists {
continue
}
if err = client.MakeBucket(context.Background(), bucket, minio.MakeBucketOptions{}); err != nil {
return c.JSON(http.StatusInternalServerError, map[string]string{
"message": "Error during minio#MakeBucket",
})
}
new_buckets = append(new_buckets, bucket)
}
var message string
if len(new_buckets) == 0 {
message = "All buckets already exist"
} else {
message = "Buckets successfully created"
}
return c.JSON(http.StatusOK, map[string]interface{}{
"message": message,
"buckets": new_buckets,
})
}
// handleV1BucketList affiche les buckets permis par server.documents.buckets, qui existent.
func handleV1BucketList(c echo.Context) error {
documents_buckets := viper.GetStringSlice("server.documents.buckets")
documents_endpoint := viper.GetString("server.documents.endpoint")
documents_access_key_id := viper.GetString("server.documents.access_key_id")
documents_secret_access_key := viper.GetString("server.documents.secret_access_key")
documents_use_ssl := viper.GetBool("server.documents.use_ssl")
// Initialize minio client object
client, err := minio.New(documents_endpoint, &minio.Options{
Creds: credentials.NewStaticV4(documents_access_key_id, documents_secret_access_key, ""),
Secure: documents_use_ssl,
})
if err != nil {
return c.JSON(http.StatusInternalServerError, map[string]string{
"message": "Error during minio#New",
})
}
var buckets []string
for _, bucket_name := range documents_buckets {
exists, err := client.BucketExists(context.Background(), bucket_name)
if err != nil {
return c.JSON(http.StatusInternalServerError, "Error during minio#BucketExists")
}
if exists {
buckets = append(buckets, bucket_name)
}
}
return c.JSON(http.StatusOK, buckets)
}
func handleV1BucketRead(c echo.Context) error {
documents_endpoint := viper.GetString("server.documents.endpoint")
documents_access_key_id := viper.GetString("server.documents.access_key_id")
documents_secret_access_key := viper.GetString("server.documents.secret_access_key")
documents_use_ssl := viper.GetBool("server.documents.use_ssl")
bucket := c.Param("bucket")
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// Initialize minio client object
client, err := minio.New(documents_endpoint, &minio.Options{
Creds: credentials.NewStaticV4(documents_access_key_id, documents_secret_access_key, ""),
Secure: documents_use_ssl,
})
if err != nil {
return c.JSON(http.StatusInternalServerError, map[string]string{
"message": "Error during minio#New",
})
}
exists, err := client.BucketExists(ctx, bucket)
if err != nil {
return c.JSON(http.StatusInternalServerError, "Error during minio#BucketExists")
}
if !exists {
return c.JSON(http.StatusNotFound, map[string]string{"message": "Not Found"})
}
var keys []string
objectCh := client.ListObjects(ctx, bucket, minio.ListObjectsOptions{})
for object := range objectCh {
if object.Err != nil {
return c.JSON(http.StatusInternalServerError, map[string]string{
"message": "Error during minio#ListObjects",
})
}
keys = append(keys, object.Key)
}
return c.JSON(http.StatusOK, keys)
}
func handleV1DocumentCreate(c echo.Context) error {
documents_endpoint := viper.GetString("server.documents.endpoint")
documents_access_key_id := viper.GetString("server.documents.access_key_id")
documents_secret_access_key := viper.GetString("server.documents.secret_access_key")
documents_use_ssl := viper.GetBool("server.documents.use_ssl")
bucket := c.Param("bucket")
form_file, err := c.FormFile("file")
if err != nil {
return err
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// Initialize minio client object
client, err := minio.New(documents_endpoint, &minio.Options{
Creds: credentials.NewStaticV4(documents_access_key_id, documents_secret_access_key, ""),
Secure: documents_use_ssl,
})
if err != nil {
return c.JSON(http.StatusInternalServerError, map[string]string{
"message": "Error during minio#New",
})
}
src, err := form_file.Open()
if err != nil {
return err
}
defer src.Close()
info, err := client.PutObject(ctx, bucket, form_file.Filename, src, form_file.Size, minio.PutObjectOptions{
ContentType: form_file.Header.Get("Content-Type"),
})
if err != nil {
return c.JSON(http.StatusInternalServerError, map[string]string{
"message": "Error during minio#PutObject",
})
}
return c.JSON(http.StatusOK, map[string]interface{}{
"message": "ok",
"info": map[string]interface{}{
"bucket": info.Bucket,
"key": info.Key,
"size": info.Size,
},
})
}
func handleV1DocumentRead(c echo.Context) error {
return c.JSON(http.StatusNotImplemented, map[string]string{
"message": "Not Implemented",
})
}
func handleV1DocumentUpdate(c echo.Context) error {
return c.JSON(http.StatusNotImplemented, map[string]string{
"message": "Not Implemented",
})
}
func handleV1DocumentDelete(c echo.Context) error {
return c.JSON(http.StatusNotImplemented, map[string]string{
"message": "Not Implemented",
})
}
// HTML Handlers
func handleIndex(c echo.Context) error {
return c.Render(http.StatusOK, "index-html", nil)
}
func handleAPropos(c echo.Context) error {
return c.Render(http.StatusOK, "a-propos-html", nil)
}
func handleActualite(c echo.Context) error {
return c.Render(http.StatusOK, "actualite-html", nil)
}
func handleActualiteArticle(c echo.Context) error {
article := c.Param("article")
return c.String(http.StatusOK, fmt.Sprintf("Article: %s", article))
}
func handleVieEtudiante(c echo.Context) error {
return c.Render(http.StatusOK, "vie-etudiante-html", nil)
}
func handleVieEtudianteOrganisme(c echo.Context) error {
organisme := c.Param("organisme")
return c.String(http.StatusOK, fmt.Sprintf("Organisme: %s", organisme))
}
func handleDocumentation(c echo.Context) error {
return c.Render(http.StatusOK, "documentation-html", nil)
}
func handleFormulaires(c echo.Context) error {
return c.Render(http.StatusOK, "formulaires-html", nil)
}
// CSS Handlers
func handleStaticCSSIndex(c echo.Context) error {
// TODO Ajouter gestion d'erreurs
data, _ := embedFS.ReadFile("css/index.css")
return c.Blob(http.StatusOK, "text/css", data)
}
func handleStaticCSSGeneral(c echo.Context) error {
// TODO Ajouter gestion d'erreurs
data, _ := embedFS.ReadFile("css/general.css")
return c.Blob(http.StatusOK, "text/css", data)
}