using AsbCloudApp.Data; using AsbCloudApp.Services; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using System.Threading; using System.Linq; using System.Threading.Tasks; using System.Collections.Generic; // For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860 namespace AsbCloudWebApi.Controllers { /// /// CRUD контроллер для админки. /// /// /// [ApiController] [Authorize] public abstract class CrudController : ControllerBase where T : IId where TService : ICrudService { protected readonly TService service; public List Roles { get; } = new List { "Администратор" }; public CrudController(TService service) { this.service = service; } /// /// Получить все записи /// /// CancellationToken /// все записи [HttpGet("all")] public virtual async Task>> GetAll(CancellationToken token = default) { if (!Roles.Any(role => User.IsInRole(role))) return Forbid(); var result = await service.GetAllAsync(token).ConfigureAwait(false); return Ok(result); } /// /// Получить одну запись по Id /// /// id записи /// /// запись [HttpGet("{id}")] public virtual async Task> Get(int id, CancellationToken token = default) { if (!Roles.Any(role => User.IsInRole(role))) return Forbid(); var result = await service.GetAsync(id, token).ConfigureAwait(false); return Ok(result); } /// /// Добавить запись /// /// запись /// /// id [HttpPost] [ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)] public virtual async Task Insert([FromBody] T value, CancellationToken token = default) { if (!Roles.Any(role => User.IsInRole(role))) return Forbid(); var result = await service.InsertAsync(value, token).ConfigureAwait(false); return Ok(result); } /// /// Редактировать запись по id /// /// id записи /// запись /// /// 1 - успешно отредактировано, 0 - нет [HttpPut("{id}")] [ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)] public virtual async Task Put(int id, [FromBody] T value, CancellationToken token = default) { if (!Roles.Any(role => User.IsInRole(role))) return Forbid(); var result = await service.UpdateAsync(id, value, token).ConfigureAwait(false); if (result == 0) return BadRequest($"id:{id} does not exist in the db"); return Ok(result); } /// /// Удалить запись по id /// /// id записи /// /// 1 - успешно удалено, 0 - нет [HttpDelete("{id}")] [ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)] public virtual async Task Delete(int id, CancellationToken token = default) { if (!Roles.Any(role => User.IsInRole(role))) return Forbid(); var result = await service.DeleteAsync(id, token).ConfigureAwait(false); return Ok(result); } } }