|
| 1 | +// Copyright (c) Six Labors. |
| 2 | +// Licensed under the Apache License, Version 2.0. |
| 3 | + |
| 4 | +using System.Collections.Generic; |
| 5 | +using System.Linq; |
| 6 | +using Microsoft.AspNetCore.Http; |
| 7 | +using Microsoft.AspNetCore.WebUtilities; |
| 8 | +using Microsoft.Extensions.Options; |
| 9 | +using Microsoft.Extensions.Primitives; |
| 10 | + |
| 11 | +namespace SixLabors.ImageSharp.Web.Commands |
| 12 | +{ |
| 13 | + /// <summary> |
| 14 | + /// Parses ImageSharp.Web image processing requests to ImageSharp.Web commands based on statically defined presets. |
| 15 | + /// The advantages of this are: |
| 16 | + /// 1. Image processing for certain scenarios can be adjusted in a single place, by adjusting the preset definition. |
| 17 | + /// 2. Security. Only known presets are applied. Limits DOS opportunities. |
| 18 | + /// </summary> |
| 19 | + public class PresetRequestParser : IRequestParser |
| 20 | + { |
| 21 | + private readonly IDictionary<string, IDictionary<string, string>> presets; |
| 22 | + |
| 23 | + public PresetRequestParser(IOptions<PresetRequestParserOptions> options) => this.presets = ParsePresets(options.Value.Presets); |
| 24 | + |
| 25 | + public IDictionary<string, string> ParseRequestCommands(HttpContext context) |
| 26 | + { |
| 27 | + var requestedPreset = context.Request.Query["preset"].ToString(); |
| 28 | + return this.presets.GetValueOrDefault(requestedPreset) ?? new Dictionary<string, string>(); |
| 29 | + } |
| 30 | + |
| 31 | + private static IDictionary<string, IDictionary<string, string>> ParsePresets(IDictionary<string, string> unparsedPresets) => |
| 32 | + unparsedPresets |
| 33 | + .Select(keyValue => new KeyValuePair<string, IDictionary<string, string>>(keyValue.Key, ParsePreset(keyValue.Value))) |
| 34 | + .ToDictionary(keyValue => keyValue.Key, keyValue => keyValue.Value); |
| 35 | + |
| 36 | + private static IDictionary<string, string> ParsePreset(string unparsedPresetValue) |
| 37 | + { |
| 38 | + Dictionary<string, StringValues> parsed = QueryHelpers.ParseQuery(unparsedPresetValue); |
| 39 | + var transformed = new Dictionary<string, string>(parsed.Count); |
| 40 | + foreach (KeyValuePair<string, StringValues> keyValue in parsed) |
| 41 | + { |
| 42 | + transformed[keyValue.Key] = keyValue.Value.ToString(); |
| 43 | + } |
| 44 | + return transformed; |
| 45 | + } |
| 46 | + } |
| 47 | +} |
0 commit comments