2024-01-22 17:22:41: merge [master:56d3e06e49d7a75f142424293788a4f3b6245430];
This commit is contained in:
1 parent
7014f56cbb
commit
2b91caece0
60 files changed
+3558
No files matched your search
@@ -0,0 +1,60 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"isp-gate-service/httperrors"
|
||||
"isp-gate-service/request"
|
||||
)
|
||||
|
||||
type AdminMethodStore interface {
|
||||
IsInnerEndpoint(path string) bool
|
||||
RequiredAdminPermission(path string) (string, bool)
|
||||
}
|
||||
|
||||
type AdminAuthorizer interface {
|
||||
AdminAuthorize(ctx context.Context, adminId int, permission string) (bool, error)
|
||||
}
|
||||
|
||||
func AdminAuthorize(store AdminMethodStore, authorizer AdminAuthorizer) Middleware {
|
||||
return func(next Handler) Handler {
|
||||
return HandlerFunc(func(ctx *request.Context) error {
|
||||
isInner := store.IsInnerEndpoint(ctx.Endpoint())
|
||||
if !isInner {
|
||||
return next.Handle(ctx)
|
||||
}
|
||||
|
||||
if !ctx.IsAdminAuthenticated() {
|
||||
return httperrors.New(
|
||||
http.StatusForbidden,
|
||||
"admin authentication required",
|
||||
errors.Errorf("admin authorization: admin authentication required for '%s'", ctx.Endpoint()),
|
||||
)
|
||||
}
|
||||
|
||||
requiredPerm, ok := store.RequiredAdminPermission(ctx.Endpoint())
|
||||
if !ok {
|
||||
return next.Handle(ctx)
|
||||
}
|
||||
|
||||
ok, err := authorizer.AdminAuthorize(ctx.Context(), ctx.AdminId(), requiredPerm)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "admin authorization: authorize")
|
||||
}
|
||||
if !ok {
|
||||
return httperrors.New(
|
||||
http.StatusForbidden,
|
||||
"endpoint is not allowed",
|
||||
errors.Errorf(
|
||||
"admin authorization: endpoint '%s' requires '%s' permission, but admin '%d' doesn't have it",
|
||||
ctx.Endpoint(), requiredPerm, ctx.AdminId(),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
return next.Handle(ctx)
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user