Add access control configuration

This commit is contained in:
Jacob Gunther 2024-03-08 21:35:02 -06:00
parent d0155e5001
commit abbc150667
No known key found for this signature in database
GPG Key ID: 3F72AFAF0F74E5FD
3 changed files with 26 additions and 11 deletions

View File

@ -6,4 +6,8 @@ cache:
enable_locks: true
java_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,
IconDuration: time.Minute * 15,
},
AccessControl: ConfigAccessControl{},
}
)
// Config represents the application configuration.
type Config struct {
Environment string `yaml:"environment"`
Host string `yaml:"host"`
Port uint16 `yaml:"port"`
Redis *string `yaml:"redis"`
Cache ConfigCache `yaml:"cache"`
Environment string `yaml:"environment"`
Host string `yaml:"host"`
Port uint16 `yaml:"port"`
Redis *string `yaml:"redis"`
Cache ConfigCache `yaml:"cache"`
AccessControl ConfigAccessControl `yaml:"access_control"`
}
// ConfigCache represents the caching durations of various responses.
@ -42,6 +44,12 @@ type ConfigCache struct {
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.
func (c *Config) ReadFile(file string) error {
data, err := os.ReadFile(file)

View File

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