Files

51 lines
1.6 KiB
Go
Raw Permalink Normal View History

2019-12-05 11:50:00 +01:00
package middleware
import (
"net/http"
"strings"
2019-12-05 11:50:00 +01:00
"time"
2022-05-04 14:49:59 +02:00
"github.com/owncloud/ocis/v2/ocis-pkg/cors"
2024-07-18 11:05:23 +02:00
rscors "github.com/rs/cors"
2019-12-05 11:50:00 +01:00
)
2020-11-16 22:13:26 +01:00
// NoCache writes required cache headers to all requests.
func NoCache(next http.Handler) http.Handler {
2019-12-05 11:50:00 +01:00
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "no-cache, no-store, max-age=0, must-revalidate, value")
w.Header().Set("Expires", "Thu, 01 Jan 1970 00:00:00 GMT")
w.Header().Set("Last-Modified", time.Now().UTC().Format(http.TimeFormat))
next.ServeHTTP(w, r)
})
}
// Cors writes required cors headers to all requests.
func Cors(opts ...cors.Option) func(http.Handler) http.Handler {
options := cors.NewOptions(opts...)
logger := options.Logger
allowCredentials := options.AllowCredentials
// A wildcard origin must not be combined with credentials.
if allowCredentials && cors.AllowsAnyOrigin(options.AllowedOrigins) {
logger.Warn().
Strs("allowed_origins", options.AllowedOrigins).
Msg("cors: refusing to allow credentials together with a wildcard origin, disabling allow_credentials")
allowCredentials = false
}
logger.Debug().
Str("allowed_origins", strings.Join(options.AllowedOrigins, ", ")).
Str("allowed_methods", strings.Join(options.AllowedMethods, ", ")).
Str("allowed_headers", strings.Join(options.AllowedHeaders, ", ")).
Bool("allow_credentials", allowCredentials).
Msg("setup cors middleware")
2024-07-18 11:05:23 +02:00
c := rscors.New(rscors.Options{
AllowedOrigins: options.AllowedOrigins,
AllowedMethods: options.AllowedMethods,
AllowedHeaders: options.AllowedHeaders,
AllowCredentials: allowCredentials,
2019-12-05 11:50:00 +01:00
})
2024-07-18 11:05:23 +02:00
return c.Handler
2019-12-05 11:50:00 +01:00
}