mirror of
https://github.com/mickael-kerjean/filestash.git
synced 2025-11-03 21:17:33 +08:00
feature (preflight): preflight to /api/files
This commit is contained in:
@ -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{},
|
||||
|
||||
@ -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()
|
||||
|
||||
@ -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))
|
||||
|
||||
Reference in New Issue
Block a user