forked from ddrilling/AsbCloudServer
CS2-123: Added CRUD over user roles and their permissions (controller + service)
This commit is contained in:
parent
872598dcdd
commit
908c855463
9
AsbCloudApp/Data/PermissionDto.cs
Normal file
9
AsbCloudApp/Data/PermissionDto.cs
Normal file
@ -0,0 +1,9 @@
|
||||
namespace AsbCloudApp.Data
|
||||
{
|
||||
public class PermissionDto
|
||||
{
|
||||
public int Id { get; set; }
|
||||
public string Caption { get; set; }
|
||||
public int Type { get; set; }
|
||||
}
|
||||
}
|
@ -6,6 +6,10 @@ namespace AsbCloudApp.Data
|
||||
{
|
||||
public int Id { get; set; }
|
||||
public string Caption { get; set; }
|
||||
public int IdParent { get; set; }
|
||||
public int RoleType { get; set; }
|
||||
public virtual ICollection<UserDto> Users { get; set; }
|
||||
public IEnumerable<int> PermissionIds { get; set; }
|
||||
public IEnumerable<PermissionDto> Permissions { get; set; }
|
||||
}
|
||||
}
|
||||
|
17
AsbCloudApp/Services/IUserRoleService.cs
Normal file
17
AsbCloudApp/Services/IUserRoleService.cs
Normal file
@ -0,0 +1,17 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using AsbCloudApp.Data;
|
||||
|
||||
|
||||
namespace AsbCloudApp.Services
|
||||
{
|
||||
public interface IUserRoleService
|
||||
{
|
||||
Task<IEnumerable<UserRoleDto>> GetAllAsync(CancellationToken token);
|
||||
Task<UserRoleDto> GetAsync(int id, CancellationToken token);
|
||||
Task<int> InsertAsync(UserRoleDto dto, CancellationToken token = default);
|
||||
Task UpdateAsync(UserRoleDto dto, CancellationToken token = default);
|
||||
Task<int> DeleteAsync(IEnumerable<int> ids, CancellationToken token);
|
||||
}
|
||||
}
|
@ -48,6 +48,7 @@ namespace AsbCloudInfrastructure
|
||||
services.AddTransient<IDrillParamsService, DrillParamsService>();
|
||||
services.AddTransient<IDrillFlowChartService, DrillFlowChartService>();
|
||||
services.AddTransient<ITimeZoneService, TimeZoneService>();
|
||||
services.AddTransient<IUserRoleService, UserRoleService>();
|
||||
|
||||
// admin crud services:
|
||||
services.AddTransient<ICrudService<DepositDto>, CrudServiceBase<DepositDto, Deposit>>();
|
||||
@ -55,7 +56,6 @@ namespace AsbCloudInfrastructure
|
||||
services.AddTransient<ICrudService<WellDto>, CrudServiceBase<WellDto, Well>>();
|
||||
services.AddTransient<ICrudService<CompanyDto>, CrudServiceBase<CompanyDto, Company>>();
|
||||
services.AddTransient<ICrudService<UserDto>, CrudServiceBase<UserDto, User>>();
|
||||
services.AddTransient<ICrudService<UserRoleDto>, CrudServiceBase<UserRoleDto, UserRole>>();
|
||||
services.AddTransient<ICrudService<TelemetryDto>, CrudServiceBase<TelemetryDto, Telemetry>>();
|
||||
services.AddTransient<ICrudService<DrillParamsDto>, DrillParamsService>();
|
||||
|
||||
|
107
AsbCloudInfrastructure/Services/UserRoleService.cs
Normal file
107
AsbCloudInfrastructure/Services/UserRoleService.cs
Normal file
@ -0,0 +1,107 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using AsbCloudApp.Data;
|
||||
using AsbCloudApp.Services;
|
||||
using AsbCloudDb.Model;
|
||||
using AsbCloudInfrastructure.Services.Cache;
|
||||
using Mapster;
|
||||
|
||||
namespace AsbCloudInfrastructure.Services
|
||||
{
|
||||
public class UserRoleService : IUserRoleService
|
||||
{
|
||||
private readonly IAsbCloudDbContext db;
|
||||
private readonly CacheTable<UserRole> cacheUserRoles;
|
||||
private readonly CacheTable<Permission> cachePermissions;
|
||||
private readonly CacheTable<RelationUserRolePermission> cacheUserRolesPermissions;
|
||||
|
||||
public UserRoleService(IAsbCloudDbContext db, CacheDb cacheDb)
|
||||
{
|
||||
this.db = db;
|
||||
cacheUserRoles = cacheDb.GetCachedTable<UserRole>((AsbCloudDbContext)db);
|
||||
cachePermissions = cacheDb.GetCachedTable<Permission>((AsbCloudDbContext)db);
|
||||
cacheUserRolesPermissions =
|
||||
cacheDb.GetCachedTable<RelationUserRolePermission>((AsbCloudDbContext)db);
|
||||
}
|
||||
|
||||
public async Task<IEnumerable<UserRoleDto>> GetAllAsync(CancellationToken token)
|
||||
{
|
||||
var rolesDtos = (await cacheUserRoles.WhereAsync(token).ConfigureAwait(false))
|
||||
.Adapt<UserRoleDto>();
|
||||
|
||||
return rolesDtos.Select(FillUserRoleWithPermissions);
|
||||
}
|
||||
|
||||
public async Task<UserRoleDto> GetAsync(int id, CancellationToken token)
|
||||
{
|
||||
var roleDto = (await cacheUserRoles.FirstOrDefaultAsync(r => r.Id == id, token)
|
||||
.ConfigureAwait(false)).Adapt<UserRoleDto>();
|
||||
|
||||
return roleDto is null ? null : FillUserRoleWithPermissions(roleDto);
|
||||
}
|
||||
|
||||
public async Task<int> InsertAsync(UserRoleDto dto, CancellationToken token = default)
|
||||
{
|
||||
var newRole = dto.Adapt<UserRole>();
|
||||
db.UserRoles.Add(newRole);
|
||||
var result = await db.SaveChangesAsync(token);
|
||||
|
||||
if (dto.PermissionIds == default)
|
||||
return result;
|
||||
|
||||
foreach (var pId in dto.PermissionIds)
|
||||
{
|
||||
var relation = new RelationUserRolePermission()
|
||||
{
|
||||
IdUserRole = newRole.Id,
|
||||
IdPermission = pId
|
||||
};
|
||||
|
||||
db.RelationUserRolesPermissions.Add(relation);
|
||||
}
|
||||
|
||||
return await db.SaveChangesAsync(token);
|
||||
}
|
||||
|
||||
public async Task UpdateAsync(UserRoleDto dto, CancellationToken token = default)
|
||||
{
|
||||
var entity = dto.Adapt<UserRole>();
|
||||
db.UserRoles.Update(entity);
|
||||
await db.SaveChangesAsync(token);
|
||||
|
||||
if (dto.PermissionIds != default)
|
||||
{
|
||||
await cacheUserRolesPermissions.RemoveAsync(r => r.IdUserRole == dto.Id, token)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
var newRelations = dto.PermissionIds.Select(p => new RelationUserRolePermission()
|
||||
{
|
||||
IdUserRole = dto.Id,
|
||||
IdPermission = p
|
||||
});
|
||||
await cacheUserRolesPermissions.InsertAsync(newRelations, token);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<int> DeleteAsync(IEnumerable<int> ids, CancellationToken token)
|
||||
{
|
||||
var entities = cacheUserRoles.Where(e => ids.Contains(e.Id));
|
||||
if (entities == default)
|
||||
return 0;
|
||||
db.UserRoles.RemoveRange(entities);
|
||||
return await db.SaveChangesAsync(token);
|
||||
}
|
||||
|
||||
private UserRoleDto FillUserRoleWithPermissions(UserRoleDto roleDto)
|
||||
{
|
||||
var rolePermissionIds = cacheUserRolesPermissions.Where(c =>
|
||||
c.IdUserRole == roleDto.Id).Select(p => p.IdPermission);
|
||||
roleDto.Permissions = cachePermissions.Where(permission => rolePermissionIds.Contains(permission.Id))
|
||||
.Adapt<PermissionDto>();
|
||||
|
||||
return roleDto;
|
||||
}
|
||||
}
|
||||
}
|
@ -1,4 +1,7 @@
|
||||
using AsbCloudApp.Data;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using AsbCloudApp.Data;
|
||||
using AsbCloudApp.Services;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
@ -8,12 +11,93 @@ namespace AsbCloudWebApi.Controllers
|
||||
[Route("api/admin/user/role")]
|
||||
[ApiController]
|
||||
[Authorize]
|
||||
public class AdminUserRoleController : CrudController<UserRoleDto, ICrudService<UserRoleDto>>
|
||||
public class AdminUserRoleController : ControllerBase
|
||||
{
|
||||
public AdminUserRoleController(ICrudService<UserRoleDto> service)
|
||||
: base(service)
|
||||
private readonly IUserRoleService userRoleService;
|
||||
|
||||
public AdminUserRoleController(IUserRoleService userRoleService)
|
||||
{
|
||||
this.userRoleService = userRoleService;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Получает список всех доступных ролей
|
||||
/// </summary>
|
||||
/// <param name="token">Токен отмены задачи</param>
|
||||
/// <returns>Список всех доступных ролей</returns>
|
||||
[HttpGet]
|
||||
[ProducesResponseType(typeof(IEnumerable<UserRoleDto>), (int)System.Net.HttpStatusCode.OK)]
|
||||
public async Task<IActionResult> GetAllAsync(CancellationToken token = default)
|
||||
{
|
||||
// TODO: Как будем делать проверку ролей пользователя? Админ, не админ.
|
||||
|
||||
var result = await userRoleService.GetAllAsync(token)
|
||||
.ConfigureAwait(false);
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Получает информацию о запрашиваемой роли
|
||||
/// </summary>
|
||||
/// <param name="idRole">id запрашиваемой задачи</param>
|
||||
/// <param name="token">Токен отмены задачи</param>
|
||||
/// <returns>Информацию о запрашиваемой роли</returns>
|
||||
[HttpGet("{idRole}")]
|
||||
[ProducesResponseType(typeof(UserRoleDto), (int)System.Net.HttpStatusCode.OK)]
|
||||
public async Task<IActionResult> GetAsync(int idRole, CancellationToken token = default)
|
||||
{
|
||||
|
||||
var result = await userRoleService.GetAsync(idRole, token)
|
||||
.ConfigureAwait(false);
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Добавить запись
|
||||
/// </summary>
|
||||
/// <param name="dto">Объект с параметрами добавляемой роли</param>
|
||||
/// <param name="token">Токен отмены задачи</param>
|
||||
/// <returns>1 - добавлено, 0 - нет</returns>
|
||||
[HttpPost]
|
||||
[ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)]
|
||||
public async Task<IActionResult> Insert([FromBody] UserRoleDto dto,
|
||||
CancellationToken token = default)
|
||||
{
|
||||
var result = await userRoleService.InsertAsync(dto, token)
|
||||
.ConfigureAwait(false);
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Редактировать запись по id
|
||||
/// </summary>
|
||||
/// <param name="dto">Объект с параметрами добавляемой роли</param>
|
||||
/// <param name="permissionIds">Id добавляемых к роли разрешений</param>
|
||||
/// <param name="token"></param>
|
||||
/// <returns>1 - успешно отредактировано, 0 - нет</returns>
|
||||
[HttpPut("{id}")]
|
||||
[ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)]
|
||||
public async Task<IActionResult> Update([FromBody] UserRoleDto dto,
|
||||
CancellationToken token = default)
|
||||
{
|
||||
|
||||
await userRoleService.UpdateAsync(dto, token).ConfigureAwait(false);
|
||||
return Ok();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Удаляет роли по указанным id
|
||||
/// </summary>
|
||||
/// <param name="ids">Список id ролей для удаления</param>
|
||||
/// <param name="token"></param>
|
||||
/// <returns></returns>
|
||||
[HttpDelete]
|
||||
[ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)]
|
||||
public async Task<IActionResult> Update(IEnumerable<int> ids, CancellationToken token = default)
|
||||
{
|
||||
|
||||
var result = await userRoleService.DeleteAsync(ids, token).ConfigureAwait(false);
|
||||
return Ok(result);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user