Files
txix 36699fdc72
Create and publish a Docker image / build-and-push-image (push) Canceled after 0s
2026-08-28 15:17:49: merge [main:657d4302881986193395aa831b36df6fd0798d4d];
2026-08-28 15:17:49 +03:00

64 lines
1.6 KiB
Go

package middleware
import (
"context"
"net/http"
"isp-gate-service/httperrors"
"isp-gate-service/request"
"github.com/txix-open/isp-kit/errors"
"github.com/txix-open/isp-kit/log"
)
type Authorizer interface {
Authorize(ctx context.Context, applicationId int, httpMethod string, pathSchema string) (bool, error)
}
func Authorize(authorizer Authorizer, logger log.Logger) Middleware {
return func(next Handler) Handler {
return HandlerFunc(func(ctx *request.Context) error {
if ctx.SkipAppAuth() {
return next.Handle(ctx)
}
authData, err := ctx.GetAuthData()
if err != nil {
return errors.WithMessage(err, "authorize: get auth data")
}
endpointMeta := ctx.EndpointMeta()
ok, err := authorizer.Authorize(
ctx.Context(),
authData.ApplicationId,
ctx.Request().Method,
endpointMeta.PathSchema,
)
if err != nil {
return errors.WithMessage(err, "authorize: authorize")
}
if !ok && ctx.IsAdminAuthenticated() {
logger.Info(
ctx.Context(),
"bypassing unauthorized request because it has admin privilege",
log.Int("applicationId", authData.ApplicationId),
log.String("applicationName", authData.AppName),
log.Int("adminId", ctx.AdminId()),
)
return next.Handle(ctx)
}
if !ok {
return httperrors.New(
http.StatusForbidden,
"endpoint is not allowed",
errors.Errorf("authorize: endpoint '%s' with http method '%s' is not allowed for application '%d'",
endpointMeta.PathSchema, ctx.Request().Method, authData.ApplicationId,
),
)
}
return next.Handle(ctx)
})
}
}