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

@@ -125,18 +125,22 @@ namespace PARR.API.Contracts.V1
public const string getParam = "{id}";
}
public static class User
{
public const string GetAll = Base + "/users/";
public const string Get = Base + "/users/" + getParam;
public const string Delete = Base + "/users/" + getParam;
public const string Create = Base + "/users/";
public const string Update = Base + "/users/" + getParam;
//public static class Layer
//{
// public const string GetAll = Base + "/layers/";
// public const string Get = Base + "/layers/" + getParam;
public const string getParam = "{id}";
}
// public const string GetAreas = Base + "/layers/" + getParam + "/areas";
// public const string GetPlaces = Base + "/layers/" + getParam + "/places";
// public const string GetTemplates = Base + "/layers/" + getParam + "/templates";
public static class Role
{
public const string GetAll = Base + "/roles/";
}
// public const string getParam = "{id}";
//
}
}

View File

@@ -0,0 +1,11 @@
namespace PARR.API.Contracts.V1.Requests
{
public class UserRequest
{
public required string Ip { get; set; }
public required string Name { get; set; }
public string Description { get; set; } = string.Empty;
}
}

View File

@@ -0,0 +1,11 @@
namespace PARR.API.Contracts.V1.Responses
{
public class RoleResponse
{
public Guid Id { get; set; }
public required string Name { get; set; }
public required string Description { get; set; }
}
}

View File

@@ -0,0 +1,17 @@
namespace PARR.API.Contracts.V1.Responses
{
public class UserResponse
{
public Guid Id { get; set; }
public DateTimeOffset DateCreated { get; set; }
public required string Ip { get; set; }
public string Name { get; set; } = string.Empty;
public string Description { get; set; } = string.Empty;
public List<RoleResponse>? Roles { get; set; }
}
}

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));
}
}
}

View File

@@ -64,7 +64,7 @@ namespace PARR.API.MappingProfiles
CreateMap<DAL.Models.Host, HostTemplateResponse>();
CreateMap<DAL.Models.Host, HostWithApplicationsResponse>()
.ForMember(d => d.Applications, o => o.MapFrom(s => s.ApplicationsInHosts.Select(t => t.Application).OrderBy(t=>t.Name)));
.ForMember(d => d.Applications, o => o.MapFrom(s => s.ApplicationsInHosts.Select(t => t.Application).OrderBy(t => t.Name)));
// === Host ===
CreateMap<RobotStatus, RobotStatusResponse>();
@@ -161,6 +161,16 @@ namespace PARR.API.MappingProfiles
.ForMember(t => t.Date, o => o.MapFrom(s => s.DateCreated))
.ForMember(t => t.Level, o => o.MapFrom(s => s.AgentHistoryLevel));
#region User
CreateMap<User, UserResponse>()
.ForMember(t => t.Roles, o => o.MapFrom(s => s.Roles.Select(t => t.Role).OrderBy(t => t!.Description)));
CreateMap<Role, RoleResponse>();
#endregion
}
}
}

View File

@@ -0,0 +1,16 @@
using FluentValidation;
using PARR.API.Contracts.V1.Requests;
namespace PARR.API.Validators
{
public class UserRequestValidator : AbstractValidator<UserRequest>
{
public UserRequestValidator()
{
RuleFor(t => t.Ip).Matches("\\b((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\\.|$)){4}\\b").WithMessage("Не является ip адресом");
RuleFor(t => t.Name).NotEmpty();
}
}
}

View File

@@ -63,7 +63,7 @@ namespace PARR.DAL
services.AddTransient<IOrderService, OrderService>();
services.AddTransient<IOrderStatusService, OrderStatusService>();
services.AddTransient<IUserService, UserService>();
services.AddTransient<IRoleService, RoleService>();
// TransformServices
services.AddTransient<IEsppScheduleTransformService, EsppScheduleTransformService>();

View File

@@ -0,0 +1,23 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using PARR.DAL.Context;
using PARR.DAL.Models;
using PARR.DAL.Services.Abstracts;
using PARR.DAL.Services.Interfaces;
namespace PARR.DAL.Services.Implementations
{
internal class RoleService : BaseService<Role>, IRoleService
{
private readonly DataContext dataContext;
public RoleService(DataContext dataContext, ILogger<RoleService> logger) : base(logger)
{
this.dataContext = dataContext;
}
protected override DbSet<Role> EntitySet => dataContext.Roles;
protected override DataContext EntitiContext => dataContext;
}
}

View File

@@ -0,0 +1,9 @@
using PARR.DAL.Models;
using PARR.DAL.Services.Interfaces.Base;
namespace PARR.DAL.Services.Interfaces
{
public interface IRoleService : IBaseService<Role>
{
}
}

View File

@@ -1,4 +1,7 @@
{
"ConnectionStrings": {
"RedisConnection": "10.99.253.216:6379,password=ParrP@ssPtk202MMdevDvs"
},
"Logging": {
"LogLevel": {
"Default": "Information",

View File

@@ -1,6 +1,7 @@
{
"ConnectionStrings": {
"DefaultConnection": "Server=10.99.253.184;Database=parr;User Id=app_parr; Password=PosdfkhT&)%sdfligL&%5546;"
"DefaultConnection": "Server=10.99.253.184;Database=parr;User Id=app_parr; Password=PosdfkhT&)%sdfligL&%5546;",
"RedisConnection": "parr-redis:6379,password=ParrP@ssPtk202MMdevDvs"
},
"Logging": {
"LogLevel": {

View File

@@ -1,4 +1,7 @@
{
"ConnectionStrings": {
"RedisConnection": "10.99.253.216:6379,password=ParrP@ssPtk202MMdevDvs"
},
"Logging": {
"LogLevel": {
"Default": "Information",

View File

@@ -1,6 +1,7 @@
{
"ConnectionStrings": {
"DefaultConnection": "Server=10.99.253.184;Database=parr;User Id=app_parr; Password=PosdfkhT&)%sdfligL&%5546;"
"DefaultConnection": "Server=10.99.253.184;Database=parr;User Id=app_parr; Password=PosdfkhT&)%sdfligL&%5546;",
"RedisConnection": "parr-redis:6379,password=ParrP@ssPtk202MMdevDvs"
},
"Logging": {
"LogLevel": {

View File

@@ -1,4 +1,7 @@
{
"ConnectionStrings": {
"RedisConnection": "10.99.253.216:6379,password=ParrP@ssPtk202MMdevDvs"
},
"Logging": {
"LogLevel": {
"Default": "Information",

View File

@@ -1,6 +1,7 @@
{
"ConnectionStrings": {
"DefaultConnection": "Server=10.99.253.184;Database=parr;User Id=app_parr; Password=PosdfkhT&)%sdfligL&%5546;"
"DefaultConnection": "Server=10.99.253.184;Database=parr;User Id=app_parr; Password=PosdfkhT&)%sdfligL&%5546;",
"RedisConnection": "parr-redis:6379,password=ParrP@ssPtk202MMdevDvs"
},
"Logging": {
"LogLevel": {

View File

@@ -1,4 +1,7 @@
{
"ConnectionStrings": {
"RedisConnection": "10.99.253.216:6379,password=ParrP@ssPtk202MMdevDvs"
},
"Logging": {
"LogLevel": {
"Default": "Information",

View File

@@ -1,6 +1,7 @@
{
"ConnectionStrings": {
"DefaultConnection": "Server=10.99.253.184;Database=parr;User Id=app_parr; Password=PosdfkhT&)%sdfligL&%5546;"
"DefaultConnection": "Server=10.99.253.184;Database=parr;User Id=app_parr; Password=PosdfkhT&)%sdfligL&%5546;",
"RedisConnection": "parr-redis:6379,password=ParrP@ssPtk202MMdevDvs"
},
"Logging": {
"LogLevel": {

View File

@@ -1,4 +1,7 @@
{
"ConnectionStrings": {
"RedisConnection": "10.99.253.216:6379,password=ParrP@ssPtk202MMdevDvs"
},
"Logging": {
"LogLevel": {
"Default": "Information",

View File

@@ -1,6 +1,7 @@
{
"ConnectionStrings": {
"DefaultConnection": "Server=10.99.253.184;Database=parr;User Id=app_parr; Password=PosdfkhT&)%sdfligL&%5546;"
"DefaultConnection": "Server=10.99.253.184;Database=parr;User Id=app_parr; Password=PosdfkhT&)%sdfligL&%5546;",
"RedisConnection": "parr-redis:6379,password=ParrP@ssPtk202MMdevDvs"
},
"Logging": {
"LogLevel": {

View File

@@ -1,4 +1,7 @@
{
"ConnectionStrings": {
"RedisConnection": "10.99.253.216:6379,password=ParrP@ssPtk202MMdevDvs"
},
"Logging": {
"LogLevel": {
"Default": "Information",

View File

@@ -1,6 +1,7 @@
{
"ConnectionStrings": {
"DefaultConnection": "Server=10.99.253.184;Database=parr;User Id=app_parr; Password=PosdfkhT&)%sdfligL&%5546;"
"DefaultConnection": "Server=10.99.253.184;Database=parr;User Id=app_parr; Password=PosdfkhT&)%sdfligL&%5546;",
"RedisConnection": "parr-redis:6379,password=ParrP@ssPtk202MMdevDvs"
},
"Logging": {
"LogLevel": {

View File

@@ -1,6 +1,7 @@
{
"ConnectionStrings": {
"DefaultConnection": "Server=10.99.253.184;Database=parr;User Id=app_parr; Password=PosdfkhT&)%sdfligL&%5546;"
"DefaultConnection": "Server=10.99.253.184;Database=parr;User Id=app_parr; Password=PosdfkhT&)%sdfligL&%5546;",
"RedisConnection": "10.99.253.216:6379,password=ParrP@ssPtk202MMdevDvs"
},
"Logging": {
"LogLevel": {

View File

@@ -1,6 +1,7 @@
{
"ConnectionStrings": {
"DefaultConnection": "Server=10.99.253.184;Database=parr;User Id=app_parr; Password=PosdfkhT&)%sdfligL&%5546;"
"DefaultConnection": "Server=10.99.253.184;Database=parr;User Id=app_parr; Password=PosdfkhT&)%sdfligL&%5546;",
"RedisConnection": "parr-redis:6379,password=ParrP@ssPtk202MMdevDvs"
},
"Logging": {
"LogLevel": {

View File

@@ -1,7 +1,8 @@
{
"ConnectionStrings": {
"DefaultConnection": "Server=10.99.253.184;Database=parr;User Id=app_parr; Password=PosdfkhT&)%sdfligL&%5546;",
"AihitConnection": "Data Source=10.248.19.97; Initial Catalog=mao2;User ID=awhit-ipp-parr;pwd=ET3h$9y1LH#D;TrustServerCertificate=true;"
"AihitConnection": "Data Source=10.248.19.97; Initial Catalog=mao2;User ID=awhit-ipp-parr;pwd=ET3h$9y1LH#D;TrustServerCertificate=true;",
"RedisConnection": "10.99.253.216:6379,password=ParrP@ssPtk202MMdevDvs"
},
"Logging": {
"LogLevel": {

View File

@@ -1,7 +1,8 @@
{
"ConnectionStrings": {
"DefaultConnection": "Server=10.99.253.184;Database=parr;User Id=app_parr; Password=PosdfkhT&)%sdfligL&%5546;",
"AihitConnection": "Data Source=10.248.19.97; Initial Catalog=mao2;User ID=awhit-ipp-parr;pwd=ET3h$9y1LH#D;TrustServerCertificate=true;"
"AihitConnection": "Data Source=10.248.19.97; Initial Catalog=mao2;User ID=awhit-ipp-parr;pwd=ET3h$9y1LH#D;TrustServerCertificate=true;",
"RedisConnection": "parr-redis:6379,password=ParrP@ssPtk202MMdevDvs"
},
"Logging": {
"LogLevel": {