summaryrefslogtreecommitdiff
path: root/app/middleware/require_user_test.go
blob: 17c0276a2413e691dadc6ed67a8774bbdb499cd3 (plain)
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
package middleware

import (
	"net/http"
	"testing"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"gitlab.com/gitlab-org/software-supply-chain-security/authorization/sparkled/app/cfg"
	"gitlab.com/gitlab-org/software-supply-chain-security/authorization/sparkled/app/domain"
	"gitlab.com/gitlab-org/software-supply-chain-security/authorization/sparkled/pkg/test"
)

func TestRequireUser(t *testing.T) {
	middleware := RequireUser(http.StatusFound, "/login")

	t.Run("when a user is not logged in", func(t *testing.T) {
		t.Run("redirects to the homepage", func(t *testing.T) {
			r, w := test.RequestResponse("GET", "/example")

			server := middleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
				require.Fail(t, "unexpected call to handler")
			}))
			server.ServeHTTP(w, r)

			require.Equal(t, http.StatusFound, w.Code)
			assert.Equal(t, "/login", w.Header().Get("Location"))
		})
	})

	t.Run("when a user is logged in", func(t *testing.T) {
		t.Run("forwards the request", func(t *testing.T) {
			r, w := test.RequestResponse("GET", "/example", test.WithContextKeyValue(t.Context(), cfg.CurrentUser, &domain.User{}))

			server := middleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
				w.WriteHeader(http.StatusTeapot)
			}))
			server.ServeHTTP(w, r)

			require.Equal(t, http.StatusTeapot, w.Code)
		})
	})
}