-
Notifications
You must be signed in to change notification settings - Fork 28
/
public_origin_middleware.go
47 lines (37 loc) · 1.34 KB
/
public_origin_middleware.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package webapp
import (
"net/http"
"net/url"
"github.com/authgear/authgear-server/pkg/lib/config"
"github.com/authgear/authgear-server/pkg/util/httputil"
"github.com/authgear/authgear-server/pkg/util/log"
)
type PublicOriginMiddlewareLogger struct{ *log.Logger }
func NewPublicOriginMiddlewareLogger(lf *log.Factory) PublicOriginMiddlewareLogger {
return PublicOriginMiddlewareLogger{lf.New("public-origin-middleware")}
}
type PublicOriginMiddleware struct {
Config *config.HTTPConfig
TrustProxy config.TrustProxy
Logger PublicOriginMiddlewareLogger
}
func (m *PublicOriginMiddleware) Handle(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
publicOrigin, err := url.Parse(m.Config.PublicOrigin)
if err != nil {
m.Logger.WithError(err).Error("failed to parse public origin")
panic(err)
}
requestScheme := httputil.GetProto(r, bool(m.TrustProxy))
requestHost := httputil.GetHost(r, bool(m.TrustProxy))
if publicOrigin.Scheme == requestScheme && publicOrigin.Host == requestHost {
next.ServeHTTP(w, r)
return
}
newURL := *r.URL
newURL.Scheme = publicOrigin.Scheme
newURL.Host = publicOrigin.Host
m.Logger.WithField("new_url", newURL).Info("redirect to the configured public origin")
http.Redirect(w, r, newURL.String(), http.StatusTemporaryRedirect)
})
}