diff --git a/server/ctrl/static.go b/server/ctrl/static.go index bcca10ff..6506fb7a 100644 --- a/server/ctrl/static.go +++ b/server/ctrl/static.go @@ -4,6 +4,7 @@ import ( _ "embed" "fmt" . "github.com/mickael-kerjean/filestash/server/common" + "github.com/mickael-kerjean/filestash/server/middleware" "io" "net/http" URL "net/url" @@ -73,6 +74,14 @@ func NotFoundHandler(ctx *App, res http.ResponseWriter, req *http.Request) { res.Write(HtmlPage404) } +func PreflightCorsOK(ctx *App, res http.ResponseWriter, req *http.Request) { + if err := middleware.EnableCors(req, res, "*"); err != nil { + SendErrorResult(res, err) + return + } + SendSuccessResult(res, nil) +} + var listOfPlugins map[string][]string = map[string][]string{ "oss": []string{}, "enterprise": []string{}, diff --git a/server/main.go b/server/main.go index 523d4a8c..f164d248 100644 --- a/server/main.go +++ b/server/main.go @@ -73,6 +73,7 @@ func Init(a App) { files.HandleFunc("/touch", NewMiddlewareChain(FileTouch, middlewares, a)).Methods("POST") middlewares = []Middleware{ApiHeaders, SessionStart, LoggedInOnly} files.HandleFunc("/search", NewMiddlewareChain(FileSearch, middlewares, a)).Methods("GET") + r.PathPrefix("/api/files").Handler(NewMiddlewareChain(PreflightCorsOK, []Middleware{}, a)).Methods("OPTIONS") // API for Shared link share := r.PathPrefix("/api/share").Subrouter() diff --git a/server/middleware/http.go b/server/middleware/http.go index 3cde7d9a..ccc523d3 100644 --- a/server/middleware/http.go +++ b/server/middleware/http.go @@ -118,26 +118,24 @@ func EnableCors(req *http.Request, res http.ResponseWriter, host string) error { if host == "" { return nil } + origin := req.Header.Get("Origin") + if origin == "" { // cors is only for browser client + return nil + } h := res.Header() if host == "*" { h.Set("Access-Control-Allow-Origin", "*") } else { - origin := req.Header.Get("Origin") - if origin == "" { - origin = req.Header.Get("Referer") - } - if origin == "" { - return nil - } u, err := url.Parse(origin) if err != nil { + Log.Debug("middleware::http origin isn't valid - '%s'", origin) return ErrNotAllowed } if u.Host != host { Log.Debug("middleware::http host missmatch for host[%s] origin[%s]", host, u.Host) return NewError("Invalid host for the selected key", 401) } - if u.Scheme == "http" && strings.HasPrefix(u.Host, "localhost:") == false { + if u.Scheme != "https" && strings.HasPrefix(u.Host, "localhost:") == false { return NewError("API access can only be done using https", 401) } h.Set("Access-Control-Allow-Origin", fmt.Sprintf("%s://%s", u.Scheme, host))