Skip to content

Commit bbdb13c

Browse files
committed
fix: cors origins parsing issue
1 parent 746f013 commit bbdb13c

3 files changed

Lines changed: 18 additions & 4 deletions

File tree

cmd/api/main.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import (
2222
"context"
2323
"os"
2424
"os/signal"
25+
"strings"
2526
"syscall"
2627
"time"
2728

@@ -221,7 +222,7 @@ func setupMiddleware(app *fiber.App, sentryHandler fiber.Handler, cfg *config.Co
221222
Format: "[${time}] ${status} - ${latency} ${method} ${path}\n",
222223
}))
223224
app.Use(cors.New(cors.Config{
224-
AllowOrigins: cfg.CORSOrigins,
225+
AllowOrigins: strings.Join(cfg.CORSOrigins, ","),
225226
AllowHeaders: "Origin, Content-Type, Accept, Authorization, X-API-Key",
226227
AllowMethods: "GET, POST, PUT, DELETE, OPTIONS, PATCH",
227228
AllowCredentials: true,

internal/config/config.go

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import (
66
"fmt"
77
"os"
88
"strconv"
9+
"strings"
910

1011
"github.com/nodebyte/backend/internal/crypto"
1112
"github.com/nodebyte/backend/internal/database"
@@ -27,7 +28,7 @@ type Config struct {
2728
APIKey string
2829

2930
// CORS
30-
CORSOrigins string
31+
CORSOrigins []string
3132

3233
// Pterodactyl Panel
3334
PterodactylURL string
@@ -68,7 +69,7 @@ func Load() (*Config, error) {
6869
DatabaseURL: os.Getenv("DATABASE_URL"),
6970
RedisURL: getEnv("REDIS_URL", "localhost:6379"),
7071
APIKey: os.Getenv("BACKEND_API_KEY"),
71-
CORSOrigins: getEnv("CORS_ORIGINS", "*"),
72+
CORSOrigins: parseCORSOrigins(getEnv("CORS_ORIGINS", "https://nodebyte.host")),
7273

7374
// Panel settings
7475
PterodactylURL: os.Getenv("PTERODACTYL_URL"),
@@ -131,6 +132,16 @@ func getEnvBool(key string, defaultValue bool) bool {
131132
return defaultValue
132133
}
133134

135+
func parseCORSOrigins(originsStr string) []string {
136+
var origins []string
137+
for _, origin := range strings.Split(originsStr, ",") {
138+
if trimmed := strings.TrimSpace(origin); trimmed != "" {
139+
origins = append(origins, trimmed)
140+
}
141+
}
142+
return origins
143+
}
144+
134145
// MergeFromDB loads configuration overrides from the `config` table in the
135146
// main application database. Values stored in the DB will overwrite the
136147
// corresponding fields on the provided Config when present.

internal/config/config_test.go

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -99,7 +99,9 @@ func TestLoad(t *testing.T) {
9999
},
100100
expectErr: false,
101101
checkFn: func(cfg *Config) bool {
102-
return cfg.CORSOrigins == "https://example.com,https://app.example.com"
102+
return len(cfg.CORSOrigins) == 2 &&
103+
cfg.CORSOrigins[0] == "https://example.com" &&
104+
cfg.CORSOrigins[1] == "https://app.example.com"
103105
},
104106
},
105107
{

0 commit comments

Comments
 (0)