Files
server/auth/cors.go
Jannis Mattheis c5fc8b7f8c fix: don't ignore cors requests in dev mode
This will make testing easier, as it's more similar to the actual prod
deployment. We don't have to rewrite anything in vite, as the host and
origin is the same.
2026-06-14 12:32:55 +02:00

53 lines
1.5 KiB
Go

package auth
import (
"regexp"
"strings"
"time"
"github.com/gin-contrib/cors"
"github.com/gotify/server/v2/config"
)
// CorsConfig generates a config to use in gin cors middleware based on server configuration.
func CorsConfig(conf *config.Configuration) cors.Config {
corsConf := cors.Config{
MaxAge: 12 * time.Hour,
AllowBrowserExtensions: true,
}
compiledOrigins := compileAllowedCORSOrigins(conf.Server.Cors.AllowOrigins)
corsConf.AllowMethods = conf.Server.Cors.AllowMethods
corsConf.AllowHeaders = conf.Server.Cors.AllowHeaders
corsConf.AllowOriginFunc = func(origin string) bool {
for _, compiledOrigin := range compiledOrigins {
if compiledOrigin.MatchString(strings.ToLower(origin)) {
return true
}
}
return false
}
if allowedOrigin := headerIgnoreCase(conf, "access-control-allow-origin"); allowedOrigin != "" && len(compiledOrigins) == 0 {
corsConf.AllowOrigins = append(corsConf.AllowOrigins, allowedOrigin)
}
return corsConf
}
func headerIgnoreCase(conf *config.Configuration, search string) (value string) {
for key, value := range conf.Server.ResponseHeaders {
if strings.ToLower(key) == search {
return value
}
}
return ""
}
func compileAllowedCORSOrigins(allowedOrigins []string) []*regexp.Regexp {
var compiledAllowedOrigins []*regexp.Regexp
for _, origin := range allowedOrigins {
compiledAllowedOrigins = append(compiledAllowedOrigins, regexp.MustCompile(origin))
}
return compiledAllowedOrigins
}