-
Notifications
You must be signed in to change notification settings - Fork 53
/
middleware.go
59 lines (52 loc) · 1.18 KB
/
middleware.go
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package rbac
import (
"context"
"net/http"
"github.com/gin-gonic/gin"
corev1 "github.com/rancher/opni/pkg/apis/core/v1"
)
type middleware struct {
provider Provider
codec HeaderCodec
}
const (
AuthorizedClusterIDsKey = "authorized_cluster_ids"
)
func (m *middleware) Handle(c *gin.Context) {
userID, ok := AuthorizedUserID(c)
if !ok {
c.AbortWithStatus(http.StatusUnauthorized)
return
}
clusters, err := m.provider.SubjectAccess(context.Background(), &corev1.SubjectAccessRequest{
Subject: userID,
})
if err != nil {
c.AbortWithStatus(http.StatusUnauthorized)
return
}
if len(clusters.Items) == 0 {
c.AbortWithStatus(http.StatusUnauthorized)
return
}
ids := make([]string, len(clusters.Items))
for i, cluster := range clusters.Items {
ids[i] = cluster.Id
}
c.Request.Header.Set(m.codec.Key(), m.codec.Encode(ids))
c.Set(AuthorizedClusterIDsKey, ids)
}
func NewMiddleware(provider Provider, codec HeaderCodec) gin.HandlerFunc {
mw := &middleware{
provider: provider,
codec: codec,
}
return mw.Handle
}
func AuthorizedClusterIDs(c *gin.Context) []string {
value, ok := c.Get(AuthorizedClusterIDsKey)
if !ok {
return nil
}
return value.([]string)
}