| | | 1 | | using Microsoft.AspNetCore.Authorization; |
| | | 2 | | using Microsoft.AspNetCore.Http; |
| | | 3 | | using Microsoft.AspNetCore.Mvc; |
| | | 4 | | using Microsoft.OpenApi; |
| | | 5 | | using Swashbuckle.AspNetCore.SwaggerGen; |
| | | 6 | | |
| | | 7 | | namespace ClutterStock.Api.Filters; |
| | | 8 | | |
| | | 9 | | internal sealed class GlobalResponsesOperationFilter : IOperationFilter |
| | | 10 | | { |
| | | 11 | | public void Apply(OpenApiOperation operation, OperationFilterContext context) |
| | | 12 | | { |
| | 0 | 13 | | if (operation.Responses is not { } responses) |
| | 0 | 14 | | operation.Responses = responses = new OpenApiResponses(); |
| | | 15 | | |
| | 0 | 16 | | var problemSchema = context.SchemaGenerator.GenerateSchema(typeof(ProblemDetails), context.SchemaRepository); |
| | 0 | 17 | | var validationSchema = context.SchemaGenerator.GenerateSchema(typeof(HttpValidationProblemDetails), context.Sche |
| | | 18 | | |
| | 0 | 19 | | responses.TryAdd("400", |
| | 0 | 20 | | new OpenApiResponse |
| | 0 | 21 | | { |
| | 0 | 22 | | Description = "Bad Request", |
| | 0 | 23 | | Content = new Dictionary<string, OpenApiMediaType> |
| | 0 | 24 | | { |
| | 0 | 25 | | ["application/problem+json"] = new() |
| | 0 | 26 | | { |
| | 0 | 27 | | Schema = validationSchema |
| | 0 | 28 | | } |
| | 0 | 29 | | } |
| | 0 | 30 | | }); |
| | | 31 | | |
| | 0 | 32 | | var allowAnonymous = context.ApiDescription.ActionDescriptor.EndpointMetadata |
| | 0 | 33 | | .OfType<IAllowAnonymous>() |
| | 0 | 34 | | .Any(); |
| | | 35 | | |
| | 0 | 36 | | if (!allowAnonymous) |
| | | 37 | | { |
| | 0 | 38 | | responses.TryAdd("401", |
| | 0 | 39 | | new OpenApiResponse |
| | 0 | 40 | | { |
| | 0 | 41 | | Description = "Unauthorized", |
| | 0 | 42 | | Content = new Dictionary<string, OpenApiMediaType> |
| | 0 | 43 | | { |
| | 0 | 44 | | ["application/problem+json"] = new() |
| | 0 | 45 | | { |
| | 0 | 46 | | Schema = problemSchema |
| | 0 | 47 | | } |
| | 0 | 48 | | } |
| | 0 | 49 | | }); |
| | | 50 | | |
| | 0 | 51 | | responses.TryAdd("403", |
| | 0 | 52 | | new OpenApiResponse |
| | 0 | 53 | | { |
| | 0 | 54 | | Description = "Forbidden", |
| | 0 | 55 | | Content = new Dictionary<string, OpenApiMediaType> |
| | 0 | 56 | | { |
| | 0 | 57 | | ["application/problem+json"] = new() |
| | 0 | 58 | | { |
| | 0 | 59 | | Schema = problemSchema |
| | 0 | 60 | | } |
| | 0 | 61 | | } |
| | 0 | 62 | | }); |
| | | 63 | | } |
| | | 64 | | |
| | 0 | 65 | | responses.TryAdd("500", |
| | 0 | 66 | | new OpenApiResponse |
| | 0 | 67 | | { |
| | 0 | 68 | | Description = "Server Error", |
| | 0 | 69 | | Content = new Dictionary<string, OpenApiMediaType> |
| | 0 | 70 | | { |
| | 0 | 71 | | ["application/problem+json"] = new() |
| | 0 | 72 | | { |
| | 0 | 73 | | Schema = problemSchema |
| | 0 | 74 | | } |
| | 0 | 75 | | } |
| | 0 | 76 | | }); |
| | 0 | 77 | | } |
| | | 78 | | } |