feat(api): управление ролями пользователя
This commit is contained in:
@@ -136,6 +136,16 @@ namespace PARR.API.Contracts.V1
|
|||||||
public const string getParam = "{id}";
|
public const string getParam = "{id}";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public static class UserRoles
|
||||||
|
{
|
||||||
|
public const string Get = Base + "/users/" + userParam + "/roles/";
|
||||||
|
public const string AddRole = Base + "/users/" + userParam + "/roles/";
|
||||||
|
public const string DeleteRole = Base + "/users/" + userParam + "/roles/" + roleParam;
|
||||||
|
|
||||||
|
public const string userParam = "{userId}";
|
||||||
|
public const string roleParam = "{roleId}";
|
||||||
|
}
|
||||||
|
|
||||||
public static class Role
|
public static class Role
|
||||||
{
|
{
|
||||||
public const string GetAll = Base + "/roles/";
|
public const string GetAll = Base + "/roles/";
|
||||||
|
|||||||
7
PARR.API/Contracts/V1/Requests/UserAddRoleRequest.cs
Normal file
7
PARR.API/Contracts/V1/Requests/UserAddRoleRequest.cs
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
namespace PARR.API.Contracts.V1.Requests
|
||||||
|
{
|
||||||
|
public class UserAddRoleRequest
|
||||||
|
{
|
||||||
|
public Guid RoleId { get; set; }
|
||||||
|
}
|
||||||
|
}
|
||||||
148
PARR.API/Controllers/V1/UserRoleController.cs
Normal file
148
PARR.API/Controllers/V1/UserRoleController.cs
Normal file
@@ -0,0 +1,148 @@
|
|||||||
|
using AutoMapper;
|
||||||
|
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.Responses;
|
||||||
|
using PARR.API.Contracts.V1.Responses.Base;
|
||||||
|
using PARR.API.Controllers.V1.Base;
|
||||||
|
using PARR.API.Services.Interfaces;
|
||||||
|
using PARR.Constants;
|
||||||
|
using PARR.DAL.Models;
|
||||||
|
using PARR.DAL.Services.Interfaces;
|
||||||
|
|
||||||
|
namespace PARR.API.Controllers.V1
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Управление ролями пользователя
|
||||||
|
/// </summary>
|
||||||
|
[Authorize(Roles = ParrRoles.Administrator.Role)]
|
||||||
|
public class UserRoleController : BaseApiController
|
||||||
|
{
|
||||||
|
private readonly IUserService userService;
|
||||||
|
private readonly IMapper mapper;
|
||||||
|
private readonly ILogger<UserRoleController> logger;
|
||||||
|
private readonly IRoleService roleService;
|
||||||
|
private readonly IAuthService authService;
|
||||||
|
private readonly IUriService uriService;
|
||||||
|
|
||||||
|
public UserRoleController(
|
||||||
|
IUserService userService,
|
||||||
|
IMapper mapper,
|
||||||
|
ILogger<UserRoleController> logger,
|
||||||
|
IRoleService roleService,
|
||||||
|
IAuthService authService,
|
||||||
|
IUriService uriService
|
||||||
|
)
|
||||||
|
{
|
||||||
|
this.userService = userService;
|
||||||
|
this.mapper = mapper;
|
||||||
|
this.logger = logger;
|
||||||
|
this.roleService = roleService;
|
||||||
|
this.authService = authService;
|
||||||
|
this.uriService = uriService;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Роли пользователя
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="userId"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
[HttpGet(ApiRoutes.UserRoles.Get)]
|
||||||
|
public async Task<IActionResult> Get([FromRoute] Guid userId)
|
||||||
|
{
|
||||||
|
var user = await userService.Get()
|
||||||
|
.Include(t => t.Roles).ThenInclude(t => t.Role)
|
||||||
|
.FirstOrDefaultAsync(t => t.Id == userId);
|
||||||
|
|
||||||
|
if (user == null)
|
||||||
|
return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = $"Не найден пользователь с id: {userId}" } }));
|
||||||
|
|
||||||
|
var response = mapper.Map<List<RoleResponse>>(user.Roles.Select(t => t.Role)).OrderBy(t => t.Description).ToList();
|
||||||
|
|
||||||
|
return Ok(new Response<List<RoleResponse>>(response, true));
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Добавить роль пользователю
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="userId"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
[HttpPost(ApiRoutes.UserRoles.AddRole)]
|
||||||
|
public async Task<IActionResult> AddRole([FromRoute] Guid userId, [FromBody] UserAddRoleRequest request)
|
||||||
|
{
|
||||||
|
var user = await userService.Get()
|
||||||
|
.Include(t => t.Roles)
|
||||||
|
.FirstOrDefaultAsync(t => t.Id == userId);
|
||||||
|
|
||||||
|
if (user == null)
|
||||||
|
return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = $"Не найден пользователь с id: {userId}" } }));
|
||||||
|
|
||||||
|
if (user.Roles.FirstOrDefault(t => t.RoleId == request.RoleId) != null)
|
||||||
|
return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = $"У пользователя {userId} уже есть роль {request.RoleId}" } }));
|
||||||
|
|
||||||
|
var newRole = await roleService.GetAsync(request.RoleId);
|
||||||
|
if (newRole == null)
|
||||||
|
return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = $"Не найдена роль с id: {request.RoleId}" } }));
|
||||||
|
|
||||||
|
// добавляем роль
|
||||||
|
user.Roles.Add(new UsersInRole { RoleId = newRole.Id });
|
||||||
|
if (!await userService.CommitAsync())
|
||||||
|
return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = $"Ошибка при добавлении роли {request.RoleId} пользователю {userId}" } }));
|
||||||
|
|
||||||
|
logger.LogInformation($"Пользователь {User.Identity?.Name} добвавил роль {newRole.Name} пользователю {userId}, {user.Ip}, {user.Name}");
|
||||||
|
|
||||||
|
// удалить из кэша
|
||||||
|
await authService.RemoveCacheUserAsync(user.Ip);
|
||||||
|
|
||||||
|
|
||||||
|
var updatedUser = await userService.Get()
|
||||||
|
.Include(t => t.Roles).ThenInclude(t => t.Role)
|
||||||
|
.FirstAsync(t => t.Id == userId);
|
||||||
|
|
||||||
|
var response = mapper.Map<List<RoleResponse>>(updatedUser.Roles.Select(t => t.Role)).OrderBy(t => t.Description).ToList();
|
||||||
|
var locationUri = uriService.GetUri(ApiRoutes.UserRoles.Get, ApiRoutes.UserRoles.userParam, userId);
|
||||||
|
|
||||||
|
return Created(locationUri, new Response<List<RoleResponse>>(response, true));
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Удалить роль у пользователя
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="userId"></param>
|
||||||
|
/// <param name="roleId"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
[HttpDelete(ApiRoutes.UserRoles.DeleteRole)]
|
||||||
|
public async Task<IActionResult> DeleteRole([FromRoute] Guid userId, [FromRoute] Guid roleId)
|
||||||
|
{
|
||||||
|
var user = await userService.Get()
|
||||||
|
.Include(t => t.Roles).ThenInclude(t => t.Role)
|
||||||
|
.FirstOrDefaultAsync(t => t.Id == userId);
|
||||||
|
|
||||||
|
if (user == null)
|
||||||
|
return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = $"Не найден пользователь с id: {userId}" } }));
|
||||||
|
|
||||||
|
var userRole = user.Roles.FirstOrDefault(t => t.RoleId == roleId);
|
||||||
|
|
||||||
|
if (userRole == null)
|
||||||
|
return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = $"У пользователя {userId} нет роли с id {roleId}" } }));
|
||||||
|
|
||||||
|
user.Roles.Remove(userRole);
|
||||||
|
|
||||||
|
if (!await userService.CommitAsync())
|
||||||
|
return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = $"Ошибка при удалении роли {roleId} у пользователя {userId}" } }));
|
||||||
|
|
||||||
|
logger.LogInformation($"Пользователь {User.Identity?.Name} удалил роль {userRole.Role.Name} у пользователя {userId}, {user.Ip}, {user.Name}");
|
||||||
|
|
||||||
|
// удалить из кэша
|
||||||
|
await authService.RemoveCacheUserAsync(user.Ip);
|
||||||
|
|
||||||
|
return NoContent();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -85,6 +85,19 @@ namespace PARR.API.Services.Implementations
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
public async Task UnlockUserAsync(string ipAddress)
|
||||||
|
{
|
||||||
|
await cacheService.DeleteCachedDataAsync(GetBlockKey(ipAddress));
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
public async Task RemoveCacheUserAsync(string ipAddress)
|
||||||
|
{
|
||||||
|
await cacheService.DeleteCachedDataAsync(GetAllowKey(ipAddress));
|
||||||
|
await cacheService.DeleteCachedDataAsync(GetBlockKey(ipAddress));
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
private string GetBlockKey(string ipAddress)
|
private string GetBlockKey(string ipAddress)
|
||||||
{
|
{
|
||||||
// d - deny
|
// d - deny
|
||||||
|
|||||||
@@ -18,5 +18,19 @@ namespace PARR.API.Services.Interfaces
|
|||||||
/// <param name="ipAddress"></param>
|
/// <param name="ipAddress"></param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
Task<bool> UserIsBlockedAsync(string ipAddress);
|
Task<bool> UserIsBlockedAsync(string ipAddress);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Удалить из кэша пользователя
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="ipAddress"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
Task RemoveCacheUserAsync(string ipAddress);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Разблокировать пользователя
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="ipAddress"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
Task UnlockUserAsync(string ipAddress);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,12 +2,52 @@
|
|||||||
{
|
{
|
||||||
public interface IRedisCacheService
|
public interface IRedisCacheService
|
||||||
{
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Получить кэшированные данные
|
||||||
|
/// </summary>
|
||||||
|
/// <typeparam name="T"></typeparam>
|
||||||
|
/// <param name="key"></param>
|
||||||
|
/// <returns></returns>
|
||||||
T? GetCachedData<T>(string key);
|
T? GetCachedData<T>(string key);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Получить кэшированные данные асинхронно
|
||||||
|
/// </summary>
|
||||||
|
/// <typeparam name="T"></typeparam>
|
||||||
|
/// <param name="key"></param>
|
||||||
|
/// <returns></returns>
|
||||||
Task<T?> GetCachedDataAsync<T>(string key);
|
Task<T?> GetCachedDataAsync<T>(string key);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Добавить в кэш данные
|
||||||
|
/// </summary>
|
||||||
|
/// <typeparam name="T"></typeparam>
|
||||||
|
/// <param name="key"></param>
|
||||||
|
/// <param name="data"></param>
|
||||||
|
/// <param name="cacheDuration"></param>
|
||||||
void SetCachedData<T>(string key, T data, TimeSpan cacheDuration);
|
void SetCachedData<T>(string key, T data, TimeSpan cacheDuration);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Добавить в кэш данные асинхронно
|
||||||
|
/// </summary>
|
||||||
|
/// <typeparam name="T"></typeparam>
|
||||||
|
/// <param name="key"></param>
|
||||||
|
/// <param name="data"></param>
|
||||||
|
/// <param name="cacheDuration"></param>
|
||||||
|
/// <returns></returns>
|
||||||
Task SetCachedDataAsync<T>(string key, T data, TimeSpan cacheDuration);
|
Task SetCachedDataAsync<T>(string key, T data, TimeSpan cacheDuration);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Удалить кэшированные данные
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="key"></param>
|
||||||
|
void DeleteCachedData(string key);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Удалить кэшированные данные асинхронно
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="key"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
Task DeleteCachedDataAsync(string key);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -58,6 +58,16 @@ namespace PARR.DAL.CacheServices
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
public async Task DeleteCachedDataAsync(string key)
|
||||||
|
{
|
||||||
|
await cache.RemoveAsync(key);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
public void DeleteCachedData(string key)
|
||||||
|
{
|
||||||
|
cache.Remove(key);
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user