Add access control configuration

This commit is contained in:
Jacob Gunther
2024-03-08 21:35:02 -06:00
parent d0155e5001
commit abbc150667
3 changed files with 26 additions and 11 deletions

View File

@@ -7,3 +7,7 @@ cache:
java_status_duration: 1m java_status_duration: 1m
bedrock_status_duration: 1m bedrock_status_duration: 1m
icon_duration: 24h icon_duration: 24h
access_control:
enable: true
allowed_origins:
- '*'

View File

@@ -22,16 +22,18 @@ var (
BedrockStatusDuration: time.Minute, BedrockStatusDuration: time.Minute,
IconDuration: time.Minute * 15, IconDuration: time.Minute * 15,
}, },
AccessControl: ConfigAccessControl{},
} }
) )
// Config represents the application configuration. // Config represents the application configuration.
type Config struct { type Config struct {
Environment string `yaml:"environment"` Environment string `yaml:"environment"`
Host string `yaml:"host"` Host string `yaml:"host"`
Port uint16 `yaml:"port"` Port uint16 `yaml:"port"`
Redis *string `yaml:"redis"` Redis *string `yaml:"redis"`
Cache ConfigCache `yaml:"cache"` Cache ConfigCache `yaml:"cache"`
AccessControl ConfigAccessControl `yaml:"access_control"`
} }
// ConfigCache represents the caching durations of various responses. // ConfigCache represents the caching durations of various responses.
@@ -42,6 +44,12 @@ type ConfigCache struct {
IconDuration time.Duration `yaml:"icon_duration"` IconDuration time.Duration `yaml:"icon_duration"`
} }
// ConfigAccessControl is the configuration for the CORS headers
type ConfigAccessControl struct {
Enable bool `yaml:"enable"`
AllowedOrigins []string `yaml:"allowed_origins"`
}
// ReadFile reads the configuration from the given file and overrides values using environment variables. // ReadFile reads the configuration from the given file and overrides values using environment variables.
func (c *Config) ReadFile(file string) error { func (c *Config) ReadFile(file string) error {
data, err := os.ReadFile(file) data, err := os.ReadFile(file)

View File

@@ -6,6 +6,7 @@ import (
"main/src/assets" "main/src/assets"
"net/http" "net/http"
"strconv" "strconv"
"strings"
"github.com/gofiber/fiber/v2" "github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/cors" "github.com/gofiber/fiber/v2/middleware/cors"
@@ -25,11 +26,13 @@ func init() {
Data: assets.Favicon, Data: assets.Favicon,
})) }))
app.Use(cors.New(cors.Config{ if config.AccessControl.Enable {
AllowOrigins: "*", app.Use(cors.New(cors.Config{
AllowMethods: "HEAD,OPTIONS,GET,POST", AllowOrigins: strings.Join(config.AccessControl.AllowedOrigins, ","),
ExposeHeaders: "X-Cache-Hit,X-Cache-Time-Remaining", AllowMethods: "HEAD,OPTIONS,GET,POST",
})) ExposeHeaders: "X-Cache-Hit,X-Cache-Time-Remaining",
}))
}
if config.Environment == "development" { if config.Environment == "development" {
app.Use(logger.New(logger.Config{ app.Use(logger.New(logger.Config{