/// <summary> /// Ensures that the user is authorized to read a single element and filters out any unauthorized content within the element. /// </summary> /// <typeparam name="T">The type of the content to be searched.</typeparam> /// <param name="content">The content being searched.</param> /// <param name="readAuthorizeObject">Executes read authorization methods against this type of object.</param> /// <param name="context">The Microsoft.AspNetCore.Mvc.Filters.ActionExecutedContext.</param> public static void Filter <T>(T content, IReadAuthorize <T> readAuthorizeObject, ActionExecutedContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (readAuthorizeObject == null) { throw new ArgumentNullException(nameof(readAuthorizeObject)); } if (!readAuthorizeObject.CanRead(content)) { context.Result = new UnauthorizedResult(); return; } readAuthorizeObject.FilterUnauthorizedContent(content); }
/// <summary> /// Filters out any unauthorized content within the collection of elements. /// </summary> /// <typeparam name="T">The type of content to be searched.</typeparam> /// <param name="objects">The content collection being searched.</param> /// <param name="readAuthorizeObject">Executes read authorization methods against this type of object.</param> /// <param name="contextResult">The context result object that contains the content collection value to be filtered.</param> public static void FilterMany <T>(IEnumerable <T> objects, IReadAuthorize <T> readAuthorizeObject, ObjectResult contextResult) { if (contextResult == null) { throw new ArgumentNullException(nameof(contextResult)); } if (readAuthorizeObject == null) { throw new ArgumentNullException(nameof(readAuthorizeObject)); } var filteredObjects = objects.Where(readAuthorizeObject.CanRead).ToList(); foreach (var @object in filteredObjects) { readAuthorizeObject.FilterUnauthorizedContent(@object); } contextResult.Value = filteredObjects; }