summaryrefslogtreecommitdiffstats
path: root/api
diff options
context:
space:
mode:
authorJoram Wilander <jwawilander@gmail.com>2016-03-04 08:08:55 -0500
committerJoram Wilander <jwawilander@gmail.com>2016-03-04 08:08:55 -0500
commitd1b1148ea8a0290a66ef7c75d1910c2558fa6186 (patch)
tree50a696f00700fca4f82459a1a7475d7bba6fcc4c /api
parent763a477c3f5de5180d5302186e06d740f8834446 (diff)
parent6b1abb404fc823be1bd0e2eeb21faaec25d03c99 (diff)
downloadchat-d1b1148ea8a0290a66ef7c75d1910c2558fa6186.tar.gz
chat-d1b1148ea8a0290a66ef7c75d1910c2558fa6186.tar.bz2
chat-d1b1148ea8a0290a66ef7c75d1910c2558fa6186.zip
Merge pull request #2307 from ZBoxApp/PLT-2112
PLT-2112: Allow CORS
Diffstat (limited to 'api')
-rw-r--r--api/context.go34
-rw-r--r--api/server.go8
2 files changed, 40 insertions, 2 deletions
diff --git a/api/context.go b/api/context.go
index 9e05c5d87..edcdcbfef 100644
--- a/api/context.go
+++ b/api/context.go
@@ -21,6 +21,15 @@ import (
var sessionCache *utils.Cache = utils.NewLru(model.SESSION_CACHE_SIZE)
+var allowedMethods []string = []string{
+ "POST",
+ "GET",
+ "OPTIONS",
+ "PUT",
+ "PATCH",
+ "DELETE",
+}
+
type Context struct {
Session model.Session
RequestId string
@@ -234,6 +243,31 @@ func (h handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}
}
+func (cw *CorsWrapper) ServeHTTP(w http.ResponseWriter, r *http.Request) {
+ if len(*utils.Cfg.ServiceSettings.AllowCorsFrom) > 0 {
+ origin := r.Header.Get("Origin")
+ if *utils.Cfg.ServiceSettings.AllowCorsFrom == "*" || strings.Contains(*utils.Cfg.ServiceSettings.AllowCorsFrom, origin) {
+ w.Header().Set("Access-Control-Allow-Origin", origin)
+
+ if r.Method == "OPTIONS" {
+ w.Header().Set(
+ "Access-Control-Allow-Methods",
+ strings.Join(allowedMethods, ", "))
+
+ w.Header().Set(
+ "Access-Control-Allow-Headers",
+ r.Header.Get("Access-Control-Request-Headers"))
+ }
+ }
+ }
+
+ if r.Method == "OPTIONS" {
+ return
+ }
+
+ cw.router.ServeHTTP(w, r)
+}
+
func GetProtocol(r *http.Request) string {
if r.Header.Get(model.HEADER_FORWARDED_PROTO) == "https" {
return "https"
diff --git a/api/server.go b/api/server.go
index 070ed7a70..b84066cbe 100644
--- a/api/server.go
+++ b/api/server.go
@@ -21,6 +21,10 @@ type Server struct {
Router *mux.Router
}
+type CorsWrapper struct {
+ router *mux.Router
+}
+
var Srv *Server
func NewServer() {
@@ -38,7 +42,7 @@ func StartServer() {
l4g.Info(utils.T("api.server.start_server.starting.info"))
l4g.Info(utils.T("api.server.start_server.listening.info"), utils.Cfg.ServiceSettings.ListenAddress)
- var handler http.Handler = Srv.Router
+ var handler http.Handler = &CorsWrapper{Srv.Router}
if utils.Cfg.RateLimitSettings.EnableRateLimiter {
l4g.Info(utils.T("api.server.start_server.rate.info"))
@@ -65,7 +69,7 @@ func StartServer() {
throttled.DefaultDeniedHandler.ServeHTTP(w, r)
})
- handler = th.Throttle(Srv.Router)
+ handler = th.Throttle(&CorsWrapper{Srv.Router})
}
go func() {