| | | 1 | | using WinSolutions.Sveta.Common.Extensions; |
| | | 2 | | using System; |
| | | 3 | | using SVETA.Api.Helpers; |
| | | 4 | | using System.Collections.Generic; |
| | | 5 | | using System.Linq; |
| | | 6 | | using System.Threading.Tasks; |
| | | 7 | | using Microsoft.AspNetCore.Mvc; |
| | | 8 | | using Microsoft.Extensions.Logging; |
| | | 9 | | using WinSolutions.Sveta.Server.Data.DataModel.Entities; |
| | | 10 | | using Microsoft.AspNetCore.Authorization; |
| | | 11 | | using SVETA.Api.Data.Domain; |
| | | 12 | | using WinSolutions.Sveta.Server.Services.Interfaces; |
| | | 13 | | using SVETA.Api.Data.DTO; |
| | | 14 | | using SVETA.Api.Helpers.Authorize; |
| | | 15 | | using WinSolutions.Sveta.Server.Data.DataModel.Kinds; |
| | | 16 | | using Swashbuckle.AspNetCore.Annotations; |
| | | 17 | | using WinSolutions.Sveta.Server.Domain; |
| | | 18 | | using WinSolutions.Sveta.Common; |
| | | 19 | | using SVETA.Api.Services.Interfaces; |
| | | 20 | | |
| | | 21 | | |
| | | 22 | | namespace SVETA.Api.Controllers |
| | | 23 | | { |
| | | 24 | | [Authorize] |
| | | 25 | | [Route("api/v1/Configuration")] |
| | | 26 | | [ApiController] |
| | | 27 | | public class ConfigurationController : SvetaController |
| | | 28 | | { |
| | | 29 | | const string _routeUrl = "api/v1/Configuration"; |
| | | 30 | | readonly IConfigurationService _service; |
| | | 31 | | readonly ILogger<ConfigurationController> _logger; |
| | | 32 | | readonly IDiskStorageService _diskStorage; |
| | | 33 | | |
| | 0 | 34 | | public ConfigurationController(IConfigurationService service, ILogger<ConfigurationController> logger, IDiskStor |
| | 0 | 35 | | { |
| | 0 | 36 | | _service = service; |
| | 0 | 37 | | _diskStorage = diskStorage; |
| | 0 | 38 | | _logger = logger; |
| | 0 | 39 | | } |
| | | 40 | | |
| | | 41 | | /// <summary> |
| | | 42 | | /// Получить все конфигурации |
| | | 43 | | /// </summary> |
| | | 44 | | /// <remarks>author i.rebenok</remarks> |
| | | 45 | | /// <param name="page">Любое значение ниже нуля изменится на 1, пагинация: номер страницы</param> |
| | | 46 | | /// <param name="limit">Любое значение ниже нуля изменится на 10, пагинация: размер страницы</param> |
| | | 47 | | /// <param name="filter">фильтр по значимым полям: секция, ключ, тип значения, значение</param> |
| | | 48 | | /// <param name="encrypted">true - выводить только ключи с шифрованными данными. По умолчанию false - выводить в |
| | | 49 | | /// <param name="sort">сортировка по одному из полей |
| | | 50 | | /// по key,key|desc, section,section|desc, valueType,valueType|desc. Сортировка по умолчанию по key</param> |
| | | 51 | | [HttpGet("")] |
| | | 52 | | [SwaggerResponse(200, "Успешно", typeof(BaseResponseDTO<ConfigurationResponseDTO>))] |
| | | 53 | | [SwaggerResponse(404, "Нет записей", typeof(ErrorDTO))] |
| | | 54 | | [SwaggerResponse(500, "Ошибка на стороне сервера", typeof(ErrorDTO))] |
| | | 55 | | [SwaggerResponse(403, "Не разрешено для этого пользователя", typeof(ErrorDTO))] |
| | | 56 | | [Authorize(Roles = Role.SystemAdmin+"," + Role.SystemOperator)] |
| | | 57 | | public async Task<IActionResult> GetConfigurations(int page = 1, int limit = 10, bool encrypted = false, string |
| | 0 | 58 | | { |
| | 0 | 59 | | filter = filter.NormalizeName(); |
| | 0 | 60 | | page = page < 1 ? 1 : page; |
| | 0 | 61 | | limit = limit < 1 ? 10 : limit; |
| | 0 | 62 | | var data = await _service.GetConfigurations(page - 1, limit, filter, sort, encrypted); |
| | 0 | 63 | | var param = $"sort={sort}&encrypted={encrypted}"; |
| | 0 | 64 | | var response = new BaseResponseDTO<ConfigurationResponseDTO>(_routeUrl, page, (int)limit, data.TotalFiltered |
| | 0 | 65 | | { |
| | 0 | 66 | | Data = data.Result.Select(x => new ConfigurationResponseDTO(x)).ToList(), |
| | 0 | 67 | | }; |
| | 0 | 68 | | return Ok(response); |
| | 0 | 69 | | } |
| | | 70 | | |
| | | 71 | | /// <summary> |
| | | 72 | | /// Получить конфигурацию по ID |
| | | 73 | | /// </summary> |
| | | 74 | | /// <remarks>author i.rebenok</remarks> |
| | | 75 | | /// <param name="id">id конфигурации</param> |
| | | 76 | | [HttpGet("{id}")] |
| | | 77 | | [SwaggerResponse(200, "Успешно", typeof(ConfigurationResponseDTO))] |
| | | 78 | | [SwaggerResponse(403, "Не разрешено для этого пользователя", typeof(ErrorDTO))] |
| | | 79 | | [SwaggerResponse(404, "Нет записей", typeof(ErrorDTO))] |
| | | 80 | | [SwaggerResponse(500, "Ошибка на стороне сервера", typeof(ErrorDTO))] |
| | | 81 | | [Authorize(Roles = Role.SystemAdmin+"," + Role.SystemOperator)] |
| | | 82 | | public async Task<IActionResult> GetConfiguration([SwaggerParameter(Required = true)] long id) |
| | 0 | 83 | | { |
| | 0 | 84 | | var result = await _service.GetConfiguration(id); |
| | 0 | 85 | | if (result == null) |
| | 0 | 86 | | return NotFoundResult($"Запись конфигурации с id={id} не найдена"); |
| | 0 | 87 | | return Ok(new ConfigurationResponseDTO(result)); |
| | 0 | 88 | | } |
| | | 89 | | |
| | | 90 | | /// <summary> |
| | | 91 | | /// Создает конфигурацию |
| | | 92 | | /// </summary> |
| | | 93 | | /// <remarks>author i.rebenok</remarks> |
| | | 94 | | /// <param name="data">ConfigurationRequestDTO</param> |
| | | 95 | | [HttpPost("")] |
| | | 96 | | [SwaggerResponse(201, "Успешно создано", typeof(ConfigurationResponseDTO))] |
| | | 97 | | [SwaggerResponse(404, "Нет записей", typeof(ErrorDTO))] |
| | | 98 | | [SwaggerResponse(400, "Некорректные входные данные", typeof(ErrorDTO))] |
| | | 99 | | [SwaggerResponse(403, "Не разрешено для этого пользователя", typeof(ErrorDTO))] |
| | | 100 | | [SwaggerResponse(500, "Ошибка на стороне сервера", typeof(ErrorDTO))] |
| | | 101 | | [Authorize(Roles = Role.SystemAdmin)] |
| | | 102 | | public async Task<IActionResult> CreateConfiguration([FromBody][SwaggerParameter(Required = true)] Configuration |
| | 0 | 103 | | { |
| | 0 | 104 | | if (!ModelState.IsValid) |
| | 0 | 105 | | return BadRequestResult("Некорректные входные данные"); |
| | 0 | 106 | | var conf = new Configuration() |
| | 0 | 107 | | { |
| | 0 | 108 | | Section = data.Section, |
| | 0 | 109 | | Key = data.Key, |
| | 0 | 110 | | Encrypted = data.Encrypted, |
| | 0 | 111 | | ValueType = (await _service.GetDataType(data.ValueTypeId)), |
| | 0 | 112 | | Value = data.Encrypted ? Convert.ToBase64String(SymmetricCrypto.EncryptData(data.Value)) : data.Value, |
| | 0 | 113 | | Description = data.Description |
| | 0 | 114 | | }; |
| | 0 | 115 | | if (conf.ValueType == null) |
| | 0 | 116 | | return NotFoundResult($"Запись типа значения с id={data.ValueTypeId} не найдена"); |
| | 0 | 117 | | if (!ValidateValueType(conf.ValueType.Name, data.Value)) |
| | 0 | 118 | | return BadRequestResult($"Значение {data.Value} не может быть приведено к типу {conf.ValueType.Name}"); |
| | 0 | 119 | | await _service.CreateConfiguration(conf); |
| | 0 | 120 | | return CreatedAtAction("GetConfiguration", new { id = conf.Id }, new ConfigurationResponseDTO(conf)); |
| | 0 | 121 | | } |
| | | 122 | | |
| | | 123 | | /// <summary> |
| | | 124 | | /// Обновляет конфигурацию |
| | | 125 | | /// </summary> |
| | | 126 | | /// <remarks>author i.rebenok</remarks> |
| | | 127 | | /// <param name="id">id конфигурации</param> |
| | | 128 | | /// <param name="data">ConfigurationRequestDTO</param> |
| | | 129 | | [HttpPut("{id}")] |
| | | 130 | | [SwaggerResponse(200, "Успешно обновлено", typeof(ConfigurationResponseDTO))] |
| | | 131 | | [SwaggerResponse(404, "Нет записей", typeof(ErrorDTO))] |
| | | 132 | | [SwaggerResponse(400, "Некорректные входные данные", typeof(ErrorDTO))] |
| | | 133 | | [SwaggerResponse(403, "Не разрешено для этого пользователя", typeof(ErrorDTO))] |
| | | 134 | | [SwaggerResponse(500, "Ошибка на стороне сервера", typeof(ErrorDTO))] |
| | | 135 | | [Authorize(Roles = Role.SystemAdmin)] |
| | | 136 | | public async Task<IActionResult> CreateConfiguration([SwaggerParameter(Required = true)] long id, [FromBody][Swa |
| | 0 | 137 | | { |
| | 0 | 138 | | if (!ModelState.IsValid) |
| | 0 | 139 | | return BadRequestResult("Некорректные входные данные"); |
| | 0 | 140 | | var conf = await _service.GetConfiguration(id); |
| | 0 | 141 | | if (conf == null) |
| | 0 | 142 | | return NotFoundResult($"Запись конфигурации с id={id} не найдена"); |
| | 0 | 143 | | conf.Section = data.Section; |
| | 0 | 144 | | conf.Key = data.Key; |
| | 0 | 145 | | conf.Encrypted = data.Encrypted; |
| | 0 | 146 | | conf.ValueType = (await _service.GetDataType(data.ValueTypeId)); |
| | 0 | 147 | | conf.Value = data.Encrypted ? Convert.ToBase64String(SymmetricCrypto.EncryptData(data.Value)) : data.Value; |
| | 0 | 148 | | conf.Description = data.Description; |
| | 0 | 149 | | if (conf.ValueType == null) |
| | 0 | 150 | | return NotFoundResult($"Запись типа значения с id={data.ValueTypeId} не найдена"); |
| | 0 | 151 | | if (!ValidateValueType(conf.ValueType.Name, data.Value)) |
| | 0 | 152 | | return BadRequestResult($"Значение {data.Value} не может быть приведено к типу {conf.ValueType.Name}"); |
| | 0 | 153 | | await _service.UpdateConfiguration(conf); |
| | 0 | 154 | | return Ok(new ConfigurationResponseDTO(conf)); |
| | 0 | 155 | | } |
| | | 156 | | |
| | | 157 | | /// <summary> |
| | | 158 | | /// Удаляет конфигурацию |
| | | 159 | | /// </summary> |
| | | 160 | | /// <remarks>author i.rebenok</remarks> |
| | | 161 | | /// <param name="id">id конфигурации</param> |
| | | 162 | | [HttpDelete("{id}")] |
| | | 163 | | [SwaggerResponse(200, "Успешно удалено", typeof(EmptyResult))] |
| | | 164 | | [SwaggerResponse(404, "Нет записей", typeof(ErrorDTO))] |
| | | 165 | | [SwaggerResponse(403, "Не разрешено для этого пользователя", typeof(ErrorDTO))] |
| | | 166 | | [SwaggerResponse(500, "Ошибка на стороне сервера", typeof(ErrorDTO))] |
| | | 167 | | [Authorize(Roles = Role.SystemAdmin)] |
| | | 168 | | public async Task<IActionResult> DeleteConfiguration([SwaggerParameter(Required = true)] long id) |
| | 0 | 169 | | { |
| | 0 | 170 | | await _service.DeleteConfiguration(id); |
| | 0 | 171 | | return Ok(); |
| | 0 | 172 | | } |
| | | 173 | | |
| | | 174 | | /// <summary> |
| | | 175 | | /// Шифрует данные |
| | | 176 | | /// </summary> |
| | | 177 | | /// <remarks>author i.rebenok</remarks> |
| | | 178 | | /// <param name="data">Данные (тип текст) для шифрования</param> |
| | | 179 | | [HttpGet("Encrypt")] |
| | | 180 | | [SwaggerResponse(200, "Успешно", typeof(string))] |
| | | 181 | | [SwaggerResponse(500, "Ошибка на стороне сервера", typeof(ErrorDTO))] |
| | | 182 | | [SwaggerResponse(403, "Не разрешено для этого пользователя", typeof(ErrorDTO))] |
| | | 183 | | [Authorize(Roles = Role.SystemAdmin)] |
| | | 184 | | public IActionResult EncryptData([SwaggerParameter(Required = true)] string data) |
| | 0 | 185 | | { |
| | 0 | 186 | | if (string.IsNullOrWhiteSpace(data)) |
| | 0 | 187 | | return BadRequestResult("Данные для шифрования не могут быть пустой строкой"); |
| | 0 | 188 | | var result = SymmetricCrypto.EncryptData(data); |
| | 0 | 189 | | return Ok(Convert.ToBase64String(result)); |
| | 0 | 190 | | } |
| | | 191 | | |
| | | 192 | | /// <summary> |
| | | 193 | | /// Дешифрует данные |
| | | 194 | | /// </summary> |
| | | 195 | | /// <remarks>author i.rebenok</remarks> |
| | | 196 | | /// <param name="data">Данные (тип текст) для дешифровки</param> |
| | | 197 | | [HttpGet("Decrypt")] |
| | | 198 | | [SwaggerResponse(200, "Успешно", typeof(string))] |
| | | 199 | | [SwaggerResponse(500, "Ошибка на стороне сервера", typeof(ErrorDTO))] |
| | | 200 | | [SwaggerResponse(403, "Не разрешено для этого пользователя", typeof(ErrorDTO))] |
| | | 201 | | [Authorize(Roles = Role.SystemAdmin)] |
| | | 202 | | public IActionResult DecryptData([SwaggerParameter(Required = true)] string data) |
| | 0 | 203 | | { |
| | 0 | 204 | | if (string.IsNullOrWhiteSpace(data)) |
| | 0 | 205 | | return BadRequestResult("Данные для дешифрования не могут быть пустой строкой"); |
| | 0 | 206 | | var result = SymmetricCrypto.DecryptData(Convert.FromBase64String(data)); |
| | 0 | 207 | | return Ok(result); |
| | 0 | 208 | | } |
| | | 209 | | |
| | | 210 | | /// <summary> |
| | | 211 | | /// Метод проверки работоспособности бэка |
| | | 212 | | /// </summary> |
| | | 213 | | /// <remarks>author i.rebenok</remarks> |
| | | 214 | | [HttpGet("HealthCheck/Backend")] |
| | | 215 | | [SwaggerResponse(200, "Успешно", typeof(DateTime))] |
| | | 216 | | [SwaggerResponse(500, "Ошибка на стороне сервера", typeof(ErrorDTO))] |
| | | 217 | | [SwaggerResponse(403, "Не разрешено для этого пользователя", typeof(ErrorDTO))] |
| | | 218 | | [AllowAnonymous] |
| | | 219 | | public IActionResult GetHealthCheckBackend() |
| | 0 | 220 | | { |
| | 0 | 221 | | return Ok(DateTime.UtcNow); |
| | 0 | 222 | | } |
| | | 223 | | |
| | | 224 | | /// <summary> |
| | | 225 | | /// Метод проверки работоспособности БД. |
| | | 226 | | /// </summary> |
| | | 227 | | /// <remarks>author i.rebenok</remarks> |
| | | 228 | | [HttpGet("HealthCheck/Database")] |
| | | 229 | | [SwaggerResponse(200, "Успешно", typeof(int))] |
| | | 230 | | [SwaggerResponse(500, "Ошибка на стороне сервера", typeof(ErrorDTO))] |
| | | 231 | | [SwaggerResponse(403, "Не разрешено для этого пользователя", typeof(ErrorDTO))] |
| | | 232 | | [AllowAnonymous] |
| | | 233 | | public async Task<IActionResult> GetHealthCheckDatabase() |
| | 0 | 234 | | { |
| | 0 | 235 | | var count = await _service.GetCountConfTypes(); |
| | 0 | 236 | | return Ok(count); |
| | 0 | 237 | | } |
| | | 238 | | |
| | | 239 | | /// <summary> |
| | | 240 | | /// Проверяет, соттветствует ли значение переданному типу |
| | | 241 | | /// </summary> |
| | | 242 | | /// <param name="valueType">Тип</param> |
| | | 243 | | /// <param name="value">Значение</param> |
| | | 244 | | /// <returns>true, если соответствует, иначе false</returns> |
| | 0 | 245 | | private bool ValidateValueType(string valueType, string value) => (valueType ?? "").ToLower() switch |
| | 0 | 246 | | { |
| | 0 | 247 | | "string" => true, |
| | 0 | 248 | | "int" => int.TryParse(value, out int _), |
| | 0 | 249 | | "datetime" => DateTime.TryParse(value, out DateTime _), |
| | 0 | 250 | | "bool" => bool.TryParse(value, out bool _), |
| | 0 | 251 | | "guid" => Guid.TryParse(value, out Guid _), |
| | 0 | 252 | | _ => false |
| | 0 | 253 | | }; |
| | | 254 | | } |
| | | 255 | | } |