feat(api): UserController - CRUD, RoleController

This commit is contained in:
Mikhail Trubnikov
2023-12-05 16:32:34 +10:00
parent 7fb1804366
commit 72a171f823
28 changed files with 380 additions and 21 deletions

View File

@@ -0,0 +1,44 @@
using AutoMapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using PARR.API.Contracts.V1;
using PARR.API.Contracts.V1.Responses;
using PARR.API.Contracts.V1.Responses.Base;
using PARR.API.Controllers.V1.Base;
using PARR.Constants;
using PARR.DAL.Services.Interfaces;
namespace PARR.API.Controllers.V1
{
[Authorize(Roles = ParrRoles.Administrator.Role)]
public class RoleController : BaseApiController
{
private readonly IRoleService roleService;
private readonly IMapper mapper;
public RoleController(
IRoleService roleService,
IMapper mapper
)
{
this.roleService = roleService;
this.mapper = mapper;
}
/// <summary>
/// Список ролей пользователей
/// </summary>
/// <returns></returns>
[HttpGet(ApiRoutes.Role.GetAll)]
public async Task<IActionResult> GetAll()
{
var roles = await roleService.Get().OrderBy(t => t.Description).ToListAsync();
var response = mapper.Map<List<RoleResponse>>(roles);
return Ok(new Response<List<RoleResponse>>(response, true));
}
}
}

View File

@@ -18,6 +18,9 @@ using PARR.DAL.Services.Interfaces;
namespace PARR.API.Controllers.V1
{
/// <summary>
/// Шаблоны
/// </summary>
[Authorize(Roles = ParrRoles.Administrator.Role)]
public class TemplateController : BaseApiController
{

View File

@@ -0,0 +1,183 @@
using AutoMapper;
using FluentValidation;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using PARR.API.Contracts.V1;
using PARR.API.Contracts.V1.Requests;
using PARR.API.Contracts.V1.Requests.Queries;
using PARR.API.Contracts.V1.Responses;
using PARR.API.Contracts.V1.Responses.Base;
using PARR.API.Controllers.V1.Base;
using PARR.API.Extensions;
using PARR.API.Services.Interfaces;
using PARR.Constants;
using PARR.DAL.DomainModels;
using PARR.DAL.Models;
using PARR.DAL.Services.Interfaces;
namespace PARR.API.Controllers.V1
{
/// <summary>
/// Управление пользователями
/// </summary>
[Authorize(Roles = ParrRoles.Administrator.Role)]
public class UserController : BaseApiController
{
private readonly IMapper mapper;
private readonly IUserService userService;
private readonly IValidator<UserRequest> validator;
private readonly IUriService uriService;
public UserController(
IMapper mapper,
IUserService userService,
IValidator<UserRequest> validator,
IUriService uriService
)
{
this.mapper = mapper;
this.userService = userService;
this.validator = validator;
this.uriService = uriService;
}
/// <summary>
/// Список пользователей постранично
/// </summary>
/// <param name="paginationQuery"></param>
/// <returns></returns>
[HttpGet(ApiRoutes.User.GetAll)]
public async Task<IActionResult> GetAll([FromQuery] PaginationQuery paginationQuery)
{
var paginationFilter = mapper.Map<PaginationFilter>(paginationQuery);
IQueryable<User> query = userService.Get()
.Include(t => t.Roles).ThenInclude(t => t.Role)
.OrderBy(t => t.Name);
var users = await userService.GetPage(query, paginationFilter).ToListAsync();
if (!users.Any())
return NoContent();
var userResponse = mapper.Map<List<UserResponse>>(users);
var paginationResponse = new PagedResponse<UserResponse>(userResponse, true).GetPaginatedProps(paginationFilter, query);
return Ok(paginationResponse);
}
/// <summary>
/// Получить пользователя по id
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[HttpGet(ApiRoutes.User.Get)]
public async Task<IActionResult> GetById([FromRoute] Guid id)
{
var user = await userService.Get()
.Include(t => t.Roles).ThenInclude(t => t.Role)
.FirstOrDefaultAsync(t => t.Id == id);
if (user == null)
return NotFound();
var response = mapper.Map<UserResponse>(user);
return Ok(new Response<UserResponse>(response, true));
}
/// <summary>
/// Удалить пользователя
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[HttpDelete(ApiRoutes.User.Delete)]
public async Task<IActionResult> Delete([FromRoute] Guid id)
{
var user = await userService.GetAsync(id);
if (user == null)
return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = $"Ошибка при удалении пользователя. Не найден пользователь с id: {id}" } }));
if (!userService.Delete(user) || !await userService.CommitAsync())
return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = $"Ошибка при удалении пользователя." } }));
return NoContent();
}
/// <summary>
/// Создать пользователя
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
[HttpPost(ApiRoutes.User.Create)]
public async Task<IActionResult> Create([FromBody] UserRequest request)
{
var resultValidate = await validator.ValidateAsync(request);
if (!resultValidate.IsValid)
return BadRequest(new Response(resultValidate.Errors));
var existIp = await userService.Get().FirstOrDefaultAsync(t => t.Ip == request.Ip);
if (existIp != null)
return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { FieldName = nameof(request.Ip), Message = $"Ip {request.Ip} занят другим пользователем." } }));
var user = new User
{
Id = Guid.NewGuid(),
Ip = request.Ip,
Name = request.Name,
Description = request.Description
};
if (!await userService.CreateAsync(user) || !await userService.CommitAsync())
return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = "Ошибка при создани пользователя." } }));
var locationUri = uriService.GetUri(ApiRoutes.User.Get, ApiRoutes.User.getParam, user.Id);
return Created(locationUri, new Response<UserResponse>(mapper.Map<UserResponse>(user), true));
}
/// <summary>
/// Обновить пользователя
/// </summary>
/// <param name="id"></param>
/// <param name="request"></param>
/// <returns></returns>
[HttpPut(ApiRoutes.User.Update)]
public async Task<IActionResult> Update([FromRoute] Guid id, [FromBody] UserRequest request)
{
var resultValidate = await validator.ValidateAsync(request);
if (!resultValidate.IsValid)
return BadRequest(new Response(resultValidate.Errors));
var orig = await userService.Get()
.Include(t => t.Roles).ThenInclude(t => t.Role)
.FirstOrDefaultAsync(t => t.Id == id);
if (orig == null)
return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = "Ошибка при изменении пользователя." } }));
//хочет изменить свой ip
if (orig.Ip != request.Ip)
{
var existIp = await userService.Get().FirstOrDefaultAsync(t => t.Ip == request.Ip);
if (existIp != null)
return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { FieldName = nameof(request.Ip), Message = $"Ip {request.Ip} занят другим пользователем." } }));
}
orig.Ip = request.Ip;
orig.Name = request.Name;
orig.Description = request.Description;
if (!await userService.CommitAsync())
return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = "Ошибка при изменении пользователя." } }));
return Ok(new Response<UserResponse>(mapper.Map<UserResponse>(orig), true));
}
}
}