101 lines
2.2 KiB
Go
101 lines
2.2 KiB
Go
package main
|
|
|
|
import (
|
|
"crypto/sha256"
|
|
"crypto/subtle"
|
|
"log"
|
|
|
|
"git.odit.services/lfk/document-server/docs" // Correct import path for docs
|
|
"git.odit.services/lfk/document-server/handlers"
|
|
"git.odit.services/lfk/document-server/models"
|
|
"github.com/gofiber/fiber/v2"
|
|
"github.com/gofiber/fiber/v2/middleware/keyauth"
|
|
"github.com/gofiber/swagger"
|
|
"github.com/spf13/viper"
|
|
)
|
|
|
|
var (
|
|
config *models.Config
|
|
)
|
|
|
|
func validateAPIKey(c *fiber.Ctx, key string) (bool, error) {
|
|
hashedAPIKey := sha256.Sum256([]byte(config.APIKey))
|
|
hashedKey := sha256.Sum256([]byte(key))
|
|
|
|
if subtle.ConstantTimeCompare(hashedAPIKey[:], hashedKey[:]) == 1 {
|
|
return true, nil
|
|
}
|
|
return false, keyauth.ErrMissingOrMalformedAPIKey
|
|
}
|
|
|
|
func loadEnv() error {
|
|
|
|
viper.SetDefault("PORT", "3000")
|
|
viper.SetDefault("CARD_BARCODEFORMAT", "ean13")
|
|
viper.SetDefault("CARD_BARCODEPREFIX", "")
|
|
viper.SetDefault("SPONSORING_BARCODEFORMAT", "code128")
|
|
viper.SetDefault("SPONSORING_BARCODEPREFIX", "")
|
|
|
|
// Load .env file
|
|
viper.SetConfigFile(".env")
|
|
|
|
// Load environment variables
|
|
viper.AutomaticEnv()
|
|
err := viper.ReadInConfig()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
// Unmarshal the config from file and env into the config struct
|
|
err = viper.Unmarshal(&config)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// @title LfK Document Server API
|
|
// @description This is the API documentation for the LfK Document Server - a tool for pdf generation.
|
|
// @securityDefinitions.apiKey ApiKeyAuth
|
|
// @in query
|
|
// @name key
|
|
func main() {
|
|
|
|
err := loadEnv()
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
|
|
handler := handlers.DefaultHandler{
|
|
Config: config,
|
|
}
|
|
|
|
// Create a new Fiber instance
|
|
app := fiber.New(fiber.Config{
|
|
Prefork: config.Prod,
|
|
})
|
|
|
|
// Swagger documentation route
|
|
app.Get("/swagger/*", swagger.HandlerDefault)
|
|
|
|
// @Security ApiKeyAuth
|
|
v1 := app.Group("/v1")
|
|
v1.Use(keyauth.New(keyauth.Config{
|
|
KeyLookup: "query:key",
|
|
Validator: validateAPIKey,
|
|
}))
|
|
|
|
v1.Get("/", func(c *fiber.Ctx) error {
|
|
return c.SendString("Hello, World!")
|
|
})
|
|
v1.Post("/contracts", handler.GenerateContract)
|
|
v1.Post("/cards", handler.GenerateCard)
|
|
v1.Post("/certificates", handler.GenerateCertificate)
|
|
|
|
app.Use(handler.NotFoundHandler)
|
|
docs.SwaggerInfo.BasePath = "/"
|
|
|
|
log.Fatal(app.Listen("0.0.0.0:" + config.Port))
|
|
}
|