summaryrefslogtreecommitdiffstats
path: root/api/context.go
diff options
context:
space:
mode:
authorElias Nahum <nahumhbl@gmail.com>2016-03-02 21:24:40 -0300
committerElias Nahum <nahumhbl@gmail.com>2016-03-02 21:24:40 -0300
commit6b1abb404fc823be1bd0e2eeb21faaec25d03c99 (patch)
tree795f65d7f068d215f8ecd239273894cd196ecd5b /api/context.go
parent3177f30829439604315563b32ace6f1305b43a66 (diff)
downloadchat-6b1abb404fc823be1bd0e2eeb21faaec25d03c99.tar.gz
chat-6b1abb404fc823be1bd0e2eeb21faaec25d03c99.tar.bz2
chat-6b1abb404fc823be1bd0e2eeb21faaec25d03c99.zip
Set CORS Headers when needed if CORS is enabled
- Enable CORS with and without RateLimiter
Diffstat (limited to 'api/context.go')
-rw-r--r--api/context.go59
1 files changed, 24 insertions, 35 deletions
diff --git a/api/context.go b/api/context.go
index 918ba3557..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
@@ -166,10 +175,6 @@ func (h handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// All api response bodies will be JSON formatted by default
w.Header().Set("Content-Type", "application/json")
- if len(*utils.Cfg.ServiceSettings.AllowCorsFrom) > 0 {
- w.Header().Set("Access-Control-Allow-Origin", *utils.Cfg.ServiceSettings.AllowCorsFrom)
- }
-
if r.Method == "GET" {
w.Header().Set("Expires", "0")
}
@@ -238,38 +243,22 @@ func (h handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}
}
-func (cw *CorsWrapper) ServeHTTP(
- w http.ResponseWriter,
- r *http.Request) {
- allowedMethods := []string{
- "POST",
- "GET",
- "OPTIONS",
- "PUT",
- "PATCH",
- "DELETE",
- }
-
- allowedHeaders := []string{
- "Accept",
- "Content-Type",
- "Content-Length",
- "Accept-Encoding",
- "Authorization",
- "X-CSRF-Token",
- "X-Auth-Token",
- }
-
+func (cw *CorsWrapper) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if len(*utils.Cfg.ServiceSettings.AllowCorsFrom) > 0 {
- w.Header().Set("Access-Control-Allow-Origin", *utils.Cfg.ServiceSettings.AllowCorsFrom)
-
- w.Header().Set(
- "Access-Control-Allow-Methods",
- strings.Join(allowedMethods, ", "))
-
- w.Header().Set(
- "Access-Control-Allow-Headers",
- strings.Join(allowedHeaders, ", "))
+ 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" {