From 695c5d6bf82f5a5c58aa0a22b4911439f08a80fb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jes=C3=BAs=20Espino?= Date: Thu, 14 Jun 2018 09:00:40 +0200 Subject: MM-10863: Handle non-API errors with redirect to webapp (#8943) * MM-10863: Handle non-API errors with redirect to webapp * Properly shutdown the app in the new test --- web/handlers.go | 8 ++++++-- web/handlers_test.go | 58 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 64 insertions(+), 2 deletions(-) create mode 100644 web/handlers_test.go (limited to 'web') diff --git a/web/handlers.go b/web/handlers.go index aac88aa3a..fe77241e3 100644 --- a/web/handlers.go +++ b/web/handlers.go @@ -157,8 +157,12 @@ func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { c.Err.IsOAuth = false } - w.WriteHeader(c.Err.StatusCode) - w.Write([]byte(c.Err.ToJson())) + if IsApiCall(r) || len(r.Header.Get("X-Mobile-App")) > 0 { + w.WriteHeader(c.Err.StatusCode) + w.Write([]byte(c.Err.ToJson())) + } else { + utils.RenderWebAppError(w, r, c.Err, c.App.AsymmetricSigningKey()) + } if c.App.Metrics != nil { c.App.Metrics.IncrementHttpError() diff --git a/web/handlers_test.go b/web/handlers_test.go new file mode 100644 index 000000000..b4c89e50f --- /dev/null +++ b/web/handlers_test.go @@ -0,0 +1,58 @@ +// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. +// See License.txt for license information. + +package web + +import ( + "net/http" + "net/http/httptest" + "testing" + + "github.com/mattermost/mattermost-server/app" + "github.com/mattermost/mattermost-server/model" + "github.com/stretchr/testify/assert" +) + +func handlerForTest(c *Context, w http.ResponseWriter, r *http.Request) { + c.Err = model.NewAppError("loginWithSaml", "api.user.saml.not_available.app_error", nil, "", http.StatusFound) +} + +func TestHandlerServeHTTPErrors(t *testing.T) { + a, err := app.New(app.StoreOverride(testStore), app.DisableConfigWatch) + defer a.Shutdown() + + web := NewWeb(a, a.Srv.Router) + if err != nil { + panic(err) + } + handler := web.NewHandler(handlerForTest) + + var flagtests = []struct { + name string + url string + mobile bool + redirect bool + }{ + {"redirect on destkop non-api endpoint", "/login/sso/saml", false, true}, + {"not redirect on destkop api endpoint", "/api/v4/test", false, false}, + {"not redirect on mobile non-api endpoint", "/login/sso/saml", true, false}, + {"not redirect on mobile api endpoint", "/api/v4/test", true, false}, + } + + for _, tt := range flagtests { + t.Run(tt.name, func(t *testing.T) { + request := httptest.NewRequest("GET", tt.url, nil) + if tt.mobile { + request.Header.Add("X-Mobile-App", "mattermost") + } + response := httptest.NewRecorder() + handler.ServeHTTP(response, request) + + if tt.redirect { + assert.Contains(t, response.Body.String(), "/error?message=") + } else { + assert.NotContains(t, response.Body.String(), "/error?message=") + } + }) + } +} -- cgit v1.2.3-1-g7c22