func (m *Middleware) IsAuthorized(resource, permission string, environment *env) func(hydcon.ContextHandler) hydcon.ContextHandler { return func(next hydcon.ContextHandler) hydcon.ContextHandler { return hydcon.ContextHandlerFunc(func(ctx context.Context, rw http.ResponseWriter, req *http.Request) { if environment == nil { environment = Env(req) } policies, err := hydcon.PoliciesFromContext(ctx) if err != nil { log.WithFields(log.Fields{"authorization": "forbidden"}).Warnf(`Policy extraction failed: "%s".`, err) errorHandler(rw, req, http.StatusForbidden) return } subject, err := hydcon.SubjectFromContext(ctx) if err != nil { log.WithFields(log.Fields{"authorization": "forbidden"}).Warnf(`Forbidden! Subject extraction failed: "%s".`, err) errorHandler(rw, req, http.StatusForbidden) return } ok, err := guard.IsGranted(resource, permission, subject, policies, environment.Ctx()) if err != nil || !ok { log.WithFields(log.Fields{"authorization": "forbidden"}).Warnf(`Forbidden! Subject "%s" is not being granted access "%s" to resource "%s".`, subject, permission, resource) errorHandler(rw, req, http.StatusForbidden) return } log.WithFields(log.Fields{"authorization": "success"}).Infof(`Allowed! Granting subject "%s" access "%s" to resource "%s".`, subject, permission, resource) next.ServeHTTPContext(ctx, rw, req) }) } }
func (m *Middleware) IsAuthorized(resource, permission string, environment *middleware.Env) func(chd.ContextHandler) chd.ContextHandler { return func(next chd.ContextHandler) chd.ContextHandler { return chd.ContextHandlerFunc(func(ctx context.Context, rw http.ResponseWriter, req *http.Request) { if environment == nil { environment = middleware.NewEnv(req) } policies, err := authcon.PoliciesFromContext(ctx) if err != nil { log.WithFields(log.Fields{ "authorization": "forbidden", "error": err, }).Warnf(`Policy extraction failed.`) pkg.HttpError(rw, errors.New("Forbidden"), http.StatusForbidden) return } subject, err := authcon.SubjectFromContext(ctx) if err != nil { log.WithFields(log.Fields{ "authorization": "forbidden", "error": err, }).Warnf(`Subject extraction failed.`) pkg.HttpError(rw, errors.New("Forbidden"), http.StatusForbidden) return } ok, err := guard.IsGranted(resource, permission, subject, policies, environment.Ctx()) if err != nil || !ok { log.WithFields(log.Fields{ "authorization": "forbidden", "error": err, "valid": ok, "subject": subject, "permission": permission, "resource": resource, }).Warnf(`Subject is not allowed perform this action on this resource.`) pkg.HttpError(rw, errors.New("Forbidden"), http.StatusForbidden) return } log.WithFields(log.Fields{ "authorization": "success", "subject": subject, "permission": permission, "resource": resource, }).Infof(`Access granted.`) next.ServeHTTPContext(ctx, rw, req) }) } }