summaryrefslogtreecommitdiff
path: root/app/middleware/require_user_test.go
blob: 92734b209508615bed5362412845eb46503944a6 (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
package middleware

import (
	"net/http"
	"testing"

	"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()

	t.Run("when a user is not logged in", func(t *testing.T) {
		t.Run("returns a 404 status", 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.StatusNotFound, w.Code)
		})
	})

	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)
		})
	})
}