Merge pull request 'Рефакторинг контроллеров РТК' (#124) from feature/process_map_permissions into dev

Reviewed-on: http://test.digitaldrilling.ru:8080/DDrilling/AsbCloudServer/pulls/124
This commit is contained in:
Никита Фролов 2023-10-05 17:49:08 +05:00
commit a6c7ddc94b
2 changed files with 58 additions and 46 deletions

View File

@ -12,6 +12,7 @@ using System.IO;
using System.Linq; using System.Linq;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using AsbCloudApp.Exceptions;
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http;
namespace AsbCloudWebApi.Controllers namespace AsbCloudWebApi.Controllers
@ -141,13 +142,13 @@ namespace AsbCloudWebApi.Controllers
/// <param name="value"></param> /// <param name="value"></param>
/// <param name="token"></param> /// <param name="token"></param>
/// <returns></returns> /// <returns></returns>
[HttpPost]
public override async Task<ActionResult<int>> InsertAsync([FromBody] ProcessMapPlanDto value, CancellationToken token) public override async Task<ActionResult<int>> InsertAsync([FromBody] ProcessMapPlanDto value, CancellationToken token)
{ {
if (!await CanUserEditProcessMapAsync(value.IdWell, token)) value.IdUser = User.GetUserId()
return Forbid(); ?? throw new ForbidException("Неизвестный пользователь");
await AssertUserHasAccessToProcessMapAsync(value.IdWell, token);
value.IdUser = User.GetUserId() ?? -1;
var result = await base.InsertAsync(value, token); var result = await base.InsertAsync(value, token);
await NotifyUsersBySignalR(value.IdWell, token); await NotifyUsersBySignalR(value.IdWell, token);
return result; return result;
@ -159,18 +160,25 @@ namespace AsbCloudWebApi.Controllers
/// <param name="value">запись</param> /// <param name="value">запись</param>
/// <param name="token"></param> /// <param name="token"></param>
/// <returns>1 - успешно отредактировано, 0 - нет</returns> /// <returns>1 - успешно отредактировано, 0 - нет</returns>
[HttpPut]
public override async Task<ActionResult<int>> UpdateAsync([FromBody] ProcessMapPlanDto value, CancellationToken token) public override async Task<ActionResult<int>> UpdateAsync([FromBody] ProcessMapPlanDto value, CancellationToken token)
{ {
if (!await CanUserEditProcessMapAsync(value.IdWell, token)) value.IdUser = User.GetUserId()
return Forbid(); ?? throw new ForbidException("Неизвестный пользователь");
value.IdUser = User.GetUserId() ?? -1; await AssertUserHasAccessToProcessMapAsync(value.IdWell, token);
var result = await base.UpdateAsync(value, token); var result = await base.UpdateAsync(value, token);
await NotifyUsersBySignalR(value.IdWell, token); await NotifyUsersBySignalR(value.IdWell, token);
return result; return result;
} }
public override async Task<ActionResult<int>> DeleteAsync(int id, CancellationToken token)
{
await AssertUserHasAccessToProcessMapAsync(id, token);
return await base.DeleteAsync(id, token);
}
/// <summary> /// <summary>
/// Возвращает шаблон файла импорта плановой РТК /// Возвращает шаблон файла импорта плановой РТК
/// </summary> /// </summary>
@ -199,13 +207,12 @@ namespace AsbCloudWebApi.Controllers
[Required] IFormFile file, [Required] IFormFile file,
CancellationToken cancellationToken) CancellationToken cancellationToken)
{ {
int? idUser = User.GetUserId(); var idUser = User.GetUserId();
if (idUser is null) if (!idUser.HasValue)
return Forbid(); throw new ForbidException("Неизвестный пользователь");
if (!await CanUserEditProcessMapAsync(idWell, cancellationToken)) await AssertUserHasAccessToProcessMapAsync(idWell, cancellationToken);
return Forbid();
if (Path.GetExtension(file.FileName).ToLower() != ".xlsx") if (Path.GetExtension(file.FileName).ToLower() != ".xlsx")
return this.ValidationBadRequest(nameof(file), "Требуется xlsx файл."); return this.ValidationBadRequest(nameof(file), "Требуется xlsx файл.");
@ -239,11 +246,6 @@ namespace AsbCloudWebApi.Controllers
[ProducesResponseType(StatusCodes.Status204NoContent)] [ProducesResponseType(StatusCodes.Status204NoContent)]
public async Task<IActionResult> ExportAsync(int idWell, CancellationToken cancellationToken) public async Task<IActionResult> ExportAsync(int idWell, CancellationToken cancellationToken)
{ {
int? idUser = User.GetUserId();
if (idUser is null)
return Forbid();
var well = await wellService.GetOrDefaultAsync(idWell, cancellationToken); var well = await wellService.GetOrDefaultAsync(idWell, cancellationToken);
if (well is null) if (well is null)
@ -254,23 +256,22 @@ namespace AsbCloudWebApi.Controllers
return File(stream, "application/octet-stream", fileName); return File(stream, "application/octet-stream", fileName);
} }
private async Task<bool> CanUserEditProcessMapAsync(int idWell, CancellationToken token) private async Task AssertUserHasAccessToProcessMapAsync(int idWell, CancellationToken cancellationToken)
{ {
var idUser = User.GetUserId(); var idUser = User.GetUserId();
if (!idUser.HasValue)
return false;
var idCompany = User.GetCompanyId(); var idCompany = User.GetCompanyId();
if (!idCompany.HasValue || !await wellService.IsCompanyInvolvedInWellAsync(idCompany.Value, idWell, token))
return false;
var well = await wellService.GetOrDefaultAsync(idWell, token);
if (well is null) if (!idCompany.HasValue || !idUser.HasValue)
return false; throw new ForbidException("Неизвестный пользователь");
return well.IdState != 2 || userRepository.HasPermission(idUser.Value, "ProcessMap.editCompletedWell"); var well = await wellService.GetOrDefaultAsync(idWell, cancellationToken)
?? throw new ForbidException($"Скважины с {idWell} не существует");
if (!await wellService.IsCompanyInvolvedInWellAsync(idCompany.Value, idWell, cancellationToken))
throw new ForbidException("Нет доступа к скважине");
if (well.IdState == 2 && !userRepository.HasPermission(idUser.Value, "ProcessMap.editCompletedWell"))
throw new ForbidException("Недостаточно прав для редактирования РТК завершённой скважины");
} }
private async Task NotifyUsersBySignalR(int idWell, CancellationToken token) private async Task NotifyUsersBySignalR(int idWell, CancellationToken token)

View File

@ -36,18 +36,17 @@ public class ProcessMapWellboreDevelopmentController : CrudWellRelatedController
/// <param name="value"></param> /// <param name="value"></param>
/// <param name="token"></param> /// <param name="token"></param>
/// <returns></returns> /// <returns></returns>
/// <exception cref="ForbidException"></exception>
public override async Task<ActionResult<int>> InsertAsync(ProcessMapWellboreDevelopmentDto value, CancellationToken token) public override async Task<ActionResult<int>> InsertAsync(ProcessMapWellboreDevelopmentDto value, CancellationToken token)
{ {
value.IdUser = User.GetUserId() value.IdUser = User.GetUserId()
?? throw new ForbidException("Неизвестный пользователь"); ?? throw new ForbidException("Неизвестный пользователь");
await AssertUserHasAccessToProcessMapWellboreDevelopmentAsync(value.IdWell, value.IdUser, token); await AssertUserHasAccessToProcessMapWellboreDevelopmentAsync(value.IdWell, token);
return await processMapWellboreDevelopmentService.InsertAsync(value, token); return await processMapWellboreDevelopmentService.InsertAsync(value, token);
} }
/// <summary> /// <summary>
/// Обновить запись проработки /// Обновить запись проработки
/// </summary> /// </summary>
/// <param name="value"></param> /// <param name="value"></param>
@ -58,12 +57,19 @@ public class ProcessMapWellboreDevelopmentController : CrudWellRelatedController
value.IdUser = User.GetUserId() value.IdUser = User.GetUserId()
?? throw new ForbidException("Неизвестный пользователь"); ?? throw new ForbidException("Неизвестный пользователь");
await AssertUserHasAccessToProcessMapWellboreDevelopmentAsync(value.IdWell, value.IdUser, token); await AssertUserHasAccessToProcessMapWellboreDevelopmentAsync(value.IdWell, token);
return await processMapWellboreDevelopmentService.UpdateAsync(value, token); return await processMapWellboreDevelopmentService.UpdateAsync(value, token);
} }
/// <summary> public override async Task<ActionResult<int>> DeleteAsync(int id, CancellationToken token)
{
await AssertUserHasAccessToProcessMapWellboreDevelopmentAsync(id, token);
return await base.DeleteAsync(id, token);
}
/// <summary>
/// Возвращает проработки по uid телеметрии /// Возвращает проработки по uid телеметрии
/// </summary> /// </summary>
/// <param name="uid">Уникальный ключ телеметрии</param> /// <param name="uid">Уникальный ключ телеметрии</param>
@ -81,16 +87,21 @@ public class ProcessMapWellboreDevelopmentController : CrudWellRelatedController
return Ok(dto); return Ok(dto);
} }
private async Task AssertUserHasAccessToProcessMapWellboreDevelopmentAsync(int idUser, int idWell, CancellationToken cancellationToken) private async Task AssertUserHasAccessToProcessMapWellboreDevelopmentAsync(int idWell, CancellationToken cancellationToken)
{ {
var well = await wellService.GetOrDefaultAsync(idWell, cancellationToken) var idUser = User.GetUserId();
var idCompany = User.GetCompanyId();
if (!idCompany.HasValue || !idUser.HasValue)
throw new ForbidException("Неизвестный пользователь");
var well = await wellService.GetOrDefaultAsync(idWell, cancellationToken)
?? throw new ForbidException($"Скважины с {idWell} не существует"); ?? throw new ForbidException($"Скважины с {idWell} не существует");
var idCompany = User.GetCompanyId(); if (!await wellService.IsCompanyInvolvedInWellAsync(idCompany.Value, idWell, cancellationToken))
if (!idCompany.HasValue || !await wellService.IsCompanyInvolvedInWellAsync(idCompany.Value, idWell, cancellationToken))
throw new ForbidException("Нет доступа к скважине"); throw new ForbidException("Нет доступа к скважине");
if (well.IdState == 2 && !userRepository.HasPermission(idUser, "ProcessMap.editCompletedWell")) if (well.IdState == 2 && !userRepository.HasPermission(idUser.Value, "ProcessMap.editCompletedWell"))
throw new ForbidException("Недостаточно прав для редактирования РТК завершённой скважины"); throw new ForbidException("Недостаточно прав для редактирования РТК завершённой скважины");
} }
} }