summaryrefslogtreecommitdiff
path: root/app/middleware/require_permission.go
blob: 91e2b72c846f358895c57d427193c53425dca092 (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
package middleware

import (
	"net/http"

	v1 "github.com/authzed/authzed-go/proto/authzed/api/v1"
	"github.com/xlgmokha/x/pkg/x"
	"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/authz"
	"gitlab.com/gitlab-org/software-supply-chain-security/authorization/sparkled/pkg/pls"
)

func RequirePermission(permission domain.Permission, client authz.CheckPermissionService) func(http.Handler) http.Handler {
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			user := cfg.CurrentUser.From(r.Context())

			reply, err := client.CheckPermission(r.Context(), permission.RequestFor(
				user,
				x.New[*domain.Sparkle](domain.WithID[*domain.Sparkle](domain.ID("*"))),
			))
			if err != nil {
				pls.LogError(r.Context(), err)
				w.WriteHeader(http.StatusForbidden)
				return
			}

			if reply.Permissionship == v1.CheckPermissionResponse_PERMISSIONSHIP_HAS_PERMISSION {
				next.ServeHTTP(w, r)
			} else {
				w.WriteHeader(http.StatusForbidden)
			}
		})
	}
}