-
Notifications
You must be signed in to change notification settings - Fork 50
/
authorization.go
52 lines (47 loc) · 1.66 KB
/
authorization.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
package security
import (
"errors"
"fmt"
"net/http"
"tweek-gateway/audit"
"github.com/sirupsen/logrus"
"github.com/urfave/negroni"
)
// AuthorizationMiddleware enforces authorization policies of incoming requests
func AuthorizationMiddleware(authorizer Authorizer, auditor audit.Auditor) negroni.HandlerFunc {
return negroni.HandlerFunc(func(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
user, ok := r.Context().Value(UserInfoKey).(UserInfo)
if !ok {
logrus.Error("Authentication failed")
auditor.TokenError(errors.New("Authentication failed"))
http.Error(rw, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
return
}
if user.Issuer() == "tweek" {
auditor.Allowed("tweek issuer", "any", "any")
next(rw, r)
} else {
sub, act, ctxs, err := ExtractFromRequest(r)
if err != nil {
logrus.WithError(err).Error("Failed to extract from request")
auditor.AuthorizerError(sub.String(), fmt.Sprintf("%q", ctxs), act, err)
http.Error(rw, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
} else {
res, err := authorizer.Authorize(r.Context(), sub, ctxs, act)
if err != nil {
logrus.WithError(err).Error("Failed to validate request")
auditor.AuthorizerError(sub.String(), fmt.Sprintf("%q", ctxs), act, err)
http.Error(rw, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
return
}
if !res {
auditor.Denied(sub.String(), fmt.Sprintf("%q", ctxs), act)
http.Error(rw, http.StatusText(http.StatusForbidden), http.StatusForbidden)
return
}
auditor.Allowed(sub.String(), fmt.Sprintf("%q", ctxs), act)
next(rw, r)
}
}
})
}