mirror of
https://github.com/Govor-team/Govor.git
synced 2026-07-21 19:54:55 +00:00
Add admin friendships controller and improve friend request handling
Introduces FriendshipsController for admin operations, including listing and removing friendships. Updates routing for admin controllers, improves error handling in UsersController, and enhances FriendsController and related services to include requester details in friendship DTOs. Refactors friend request acceptance to use query parameters and updates console client for improved user feedback and local development configuration.
This commit is contained in:
@@ -0,0 +1,109 @@
|
|||||||
|
using Govor.Contracts.DTOs;
|
||||||
|
using Govor.Core.Models;
|
||||||
|
using Govor.Core.Repositories.Friendships;
|
||||||
|
using Govor.Data.Repositories.Exceptions;
|
||||||
|
using Microsoft.AspNetCore.Authorization;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
|
||||||
|
namespace Govor.API.Controllers.AdminStuff;
|
||||||
|
|
||||||
|
[ApiController]
|
||||||
|
[Route("api/admin/[controller]")]
|
||||||
|
[Authorize(Roles = "Admin")]
|
||||||
|
public class FriendshipsController : Controller
|
||||||
|
{
|
||||||
|
private readonly ILogger<FriendshipsController> _logger;
|
||||||
|
private readonly IFriendshipsRepository _friendshipsRepository;
|
||||||
|
|
||||||
|
public FriendshipsController(ILogger<FriendshipsController> logger, IFriendshipsRepository friendshipsRepository)
|
||||||
|
{
|
||||||
|
_logger = logger;
|
||||||
|
_friendshipsRepository = friendshipsRepository;
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpGet]
|
||||||
|
public async Task<IActionResult> Get()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
_logger.LogInformation("Get all friendships by administrator");
|
||||||
|
var result = await _friendshipsRepository.GetAllAsync();
|
||||||
|
return Ok(BuildFriendshipDtos(result));
|
||||||
|
}
|
||||||
|
catch (NotFoundException ex)
|
||||||
|
{
|
||||||
|
_logger.LogWarning(ex.Message);
|
||||||
|
return NotFound(ex.Message);
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
_logger.LogError(e, e.Message);
|
||||||
|
return StatusCode(500, new { error = "Internal server error." });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpGet("{userId}")]
|
||||||
|
public async Task<IActionResult> GetByUserId(Guid userId)
|
||||||
|
{
|
||||||
|
if(userId == Guid.Empty)
|
||||||
|
return BadRequest("User id can't be empty.");
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
_logger.LogInformation($"Get user's {userId} all friendships by administrator");
|
||||||
|
var result = await _friendshipsRepository.FindByUserIdAsync(userId);
|
||||||
|
return Ok(BuildFriendshipDtos(result));
|
||||||
|
}
|
||||||
|
catch (NotFoundByKeyException<Guid> ex)
|
||||||
|
{
|
||||||
|
_logger.LogWarning(ex.Message);
|
||||||
|
return NotFound(ex.Message);
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
_logger.LogError(e, e.Message);
|
||||||
|
return StatusCode(500, new { error = "Internal server error." });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpPost]
|
||||||
|
public async Task<IActionResult> RemoveFriendship(Guid Id)
|
||||||
|
{
|
||||||
|
if(Id == Guid.Empty)
|
||||||
|
return BadRequest("FS id can't be empty.");
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var result = await _friendshipsRepository.GetByIdAsync(Id);
|
||||||
|
await _friendshipsRepository.RemoveAsync(result);
|
||||||
|
return Ok();
|
||||||
|
}
|
||||||
|
catch (NotFoundByKeyException<Guid> ex)
|
||||||
|
{
|
||||||
|
_logger.LogWarning(ex.Message);
|
||||||
|
return NotFound(ex.Message);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex, ex.Message);
|
||||||
|
return StatusCode(500, new { error = "Internal server error." });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<UserDto> BuildUserDtos(IEnumerable<User> users) => users.Select(user => new UserDto
|
||||||
|
{
|
||||||
|
Id = user.Id,
|
||||||
|
Username = user.Username,
|
||||||
|
Description = user.Description,
|
||||||
|
WasOnline = user.WasOnline,
|
||||||
|
IconId = user.IconId
|
||||||
|
}).ToList();
|
||||||
|
|
||||||
|
private List<FriendshipDto> BuildFriendshipDtos(IEnumerable<Friendship> friendships) => friendships.Select(f => new FriendshipDto
|
||||||
|
{
|
||||||
|
Id = f.Id,
|
||||||
|
Status = f.Status,
|
||||||
|
AddresseeId = f.AddresseeId,
|
||||||
|
RequesterId = f.RequesterId,
|
||||||
|
Requester = BuildUserDtos([f.Requester]).First(),
|
||||||
|
}).ToList();
|
||||||
|
}
|
||||||
@@ -7,7 +7,7 @@ using Microsoft.AspNetCore.Mvc;
|
|||||||
|
|
||||||
namespace Govor.API.Controllers.AdminStuff;
|
namespace Govor.API.Controllers.AdminStuff;
|
||||||
|
|
||||||
[Route("api/[controller]")]
|
[Route("api/admin/[controller]")]
|
||||||
[ApiController]
|
[ApiController]
|
||||||
[Authorize(Roles = "Admin")]
|
[Authorize(Roles = "Admin")]
|
||||||
public class InviteUserController : Controller
|
public class InviteUserController : Controller
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
using Govor.API.Services.AdminsStuff.Interfaces;
|
using Govor.API.Services.AdminsStuff.Interfaces;
|
||||||
using Govor.Contracts.Responses.Admins;
|
using Govor.Contracts.Responses.Admins;
|
||||||
using Govor.Core.Models;
|
using Govor.Core.Models;
|
||||||
|
using Govor.Data.Repositories.Exceptions;
|
||||||
using Microsoft.AspNetCore.Authorization;
|
using Microsoft.AspNetCore.Authorization;
|
||||||
using Microsoft.AspNetCore.Mvc;
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
|
||||||
@@ -48,6 +49,11 @@ public class UsersController : Controller
|
|||||||
var read = await _users.GetUserById(id);
|
var read = await _users.GetUserById(id);
|
||||||
return Ok(BuildUserDtos([read]).First());
|
return Ok(BuildUserDtos([read]).First());
|
||||||
}
|
}
|
||||||
|
catch (NotFoundByKeyException<Guid> ex)
|
||||||
|
{
|
||||||
|
_logger.LogWarning(ex, ex.Message);
|
||||||
|
return NotFound(ex.Message);
|
||||||
|
}
|
||||||
catch (Exception e)
|
catch (Exception e)
|
||||||
{
|
{
|
||||||
_logger.LogError(e, e.Message);
|
_logger.LogError(e, e.Message);
|
||||||
@@ -55,6 +61,7 @@ public class UsersController : Controller
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
private List<UserResponse> BuildUserDtos(IEnumerable<User> users) => users.Select(user => new UserResponse
|
private List<UserResponse> BuildUserDtos(IEnumerable<User> users) => users.Select(user => new UserResponse
|
||||||
{
|
{
|
||||||
Id = user.Id,
|
Id = user.Id,
|
||||||
|
|||||||
@@ -98,7 +98,7 @@ public class FriendsController : Controller
|
|||||||
}
|
}
|
||||||
|
|
||||||
[HttpPost("accept")]
|
[HttpPost("accept")]
|
||||||
public async Task<IActionResult> AcceptFriend(Guid friendshipId)
|
public async Task<IActionResult> AcceptFriend([FromQuery] Guid friendshipId)
|
||||||
{
|
{
|
||||||
if (friendshipId == Guid.Empty)
|
if (friendshipId == Guid.Empty)
|
||||||
return BadRequest("Requester ID is invalid");
|
return BadRequest("Requester ID is invalid");
|
||||||
@@ -159,6 +159,7 @@ public class FriendsController : Controller
|
|||||||
Id = f.Id,
|
Id = f.Id,
|
||||||
Status = f.Status,
|
Status = f.Status,
|
||||||
AddresseeId = f.AddresseeId,
|
AddresseeId = f.AddresseeId,
|
||||||
RequesterId = f.RequesterId
|
RequesterId = f.RequesterId,
|
||||||
|
Requester = BuildUserDtos([f.Requester]).First(),
|
||||||
}).ToList();
|
}).ToList();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -90,6 +90,7 @@ public class FriendsService : IFriendsService
|
|||||||
var friendships = await _friendshipsRepository.FindByUserIdAsync(userId);
|
var friendships = await _friendshipsRepository.FindByUserIdAsync(userId);
|
||||||
|
|
||||||
return friendships
|
return friendships
|
||||||
|
.Where(f => f.Status == FriendshipStatus.Accepted)
|
||||||
.Select(f => f.RequesterId == userId ? f.Addressee : f.Requester)
|
.Select(f => f.RequesterId == userId ? f.Addressee : f.Requester)
|
||||||
.ToList();
|
.ToList();
|
||||||
}
|
}
|
||||||
@@ -103,10 +104,8 @@ public class FriendsService : IFriendsService
|
|||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
var user = await _usersRepository.FindByIdAsync(userId);
|
var friendships = await _friendshipsRepository.FindByUserIdAsync(userId);
|
||||||
return user.ReceivedFriendRequests
|
return friendships.Where(f => f.AddresseeId == userId && f.Status == FriendshipStatus.Pending).ToList();
|
||||||
.Where(f => f.Status == FriendshipStatus.Pending)
|
|
||||||
.ToList();
|
|
||||||
}
|
}
|
||||||
catch (NotFoundByKeyException<Guid> ex)
|
catch (NotFoundByKeyException<Guid> ex)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -36,8 +36,7 @@ namespace Govor.ConsoleClient
|
|||||||
|
|
||||||
public async Task AcceptFriendRequestAsync(Guid requesterId)
|
public async Task AcceptFriendRequestAsync(Guid requesterId)
|
||||||
{
|
{
|
||||||
var content = JsonContent.Create(requesterId);
|
var response = await _client.PostAsync($"/api/friends/accept?friendshipId={requesterId}", null);
|
||||||
var response = await _client.PostAsync("/api/friends/accept", content);
|
|
||||||
response.EnsureSuccessStatusCode();
|
response.EnsureSuccessStatusCode();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -25,8 +25,10 @@ namespace Govor.ConsoleClient
|
|||||||
{
|
{
|
||||||
class Program
|
class Program
|
||||||
{
|
{
|
||||||
|
//static string baseUrl = "https://govor-team-govor-88b3.twc1.net";
|
||||||
|
static string baseUrl = "https://localhost:7155";
|
||||||
static string? AuthToken = null;
|
static string? AuthToken = null;
|
||||||
static HttpClientService HttpService = new("https://govor-team-govor-88b3.twc1.net"); // поменяй URL на свой
|
static HttpClientService HttpService = new(baseUrl); // поменяй URL на свой
|
||||||
private static FriendsClient? friendsClient;
|
private static FriendsClient? friendsClient;
|
||||||
static HubConnection? _hubConnection;
|
static HubConnection? _hubConnection;
|
||||||
static Dictionary<string, List<string>> ChatHistory = new();
|
static Dictionary<string, List<string>> ChatHistory = new();
|
||||||
@@ -72,7 +74,7 @@ namespace Govor.ConsoleClient
|
|||||||
{
|
{
|
||||||
AuthToken = await HttpService.LoginAsync(loginUsername, loginPassword);
|
AuthToken = await HttpService.LoginAsync(loginUsername, loginPassword);
|
||||||
HttpClient sharedClient = new();
|
HttpClient sharedClient = new();
|
||||||
sharedClient.BaseAddress = new Uri("https://govor-team-govor-88b3.twc1.net");
|
sharedClient.BaseAddress = new Uri(baseUrl);
|
||||||
sharedClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AuthToken);
|
sharedClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AuthToken);
|
||||||
|
|
||||||
friendsClient = new FriendsClient(sharedClient);
|
friendsClient = new FriendsClient(sharedClient);
|
||||||
@@ -98,7 +100,7 @@ namespace Govor.ConsoleClient
|
|||||||
{
|
{
|
||||||
AuthToken = await HttpService.RegisterAsync(regUsername, regPassword, inviteCode);
|
AuthToken = await HttpService.RegisterAsync(regUsername, regPassword, inviteCode);
|
||||||
HttpClient sharedClient = new();
|
HttpClient sharedClient = new();
|
||||||
sharedClient.BaseAddress = new Uri("https://govor-team-govor-88b3.twc1.net");
|
sharedClient.BaseAddress = new Uri(baseUrl);
|
||||||
sharedClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AuthToken);
|
sharedClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AuthToken);
|
||||||
|
|
||||||
friendsClient = new FriendsClient(sharedClient);
|
friendsClient = new FriendsClient(sharedClient);
|
||||||
@@ -165,7 +167,7 @@ namespace Govor.ConsoleClient
|
|||||||
Console.WriteLine("[Ошибка] Сначала войдите в систему.");
|
Console.WriteLine("[Ошибка] Сначала войдите в систему.");
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
Console.Write("Введите ID пользователя, чью заявку принимаете: ");
|
Console.Write("Введите ID заявки, которую хотите принять принимаете: ");
|
||||||
var acceptId = Guid.Parse(Console.ReadLine());
|
var acceptId = Guid.Parse(Console.ReadLine());
|
||||||
await friendsClient.AcceptFriendRequestAsync(acceptId);
|
await friendsClient.AcceptFriendRequestAsync(acceptId);
|
||||||
Console.WriteLine("Принято");
|
Console.WriteLine("Принято");
|
||||||
@@ -179,7 +181,7 @@ namespace Govor.ConsoleClient
|
|||||||
var requests = await friendsClient.GetIncomingRequestsAsync();
|
var requests = await friendsClient.GetIncomingRequestsAsync();
|
||||||
foreach (var r in requests)
|
foreach (var r in requests)
|
||||||
{
|
{
|
||||||
Console.WriteLine($"Запрос от: {r.RequesterId} (добавьте через /accept {r.RequesterId})");
|
Console.WriteLine($"Запрос от: {r.Requester.Username}| {r.RequesterId} | Был онлайн: {r.Requester.WasOnline} (добавьте через /accept {r.Id})");
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
case "/chat":
|
case "/chat":
|
||||||
@@ -221,7 +223,7 @@ namespace Govor.ConsoleClient
|
|||||||
}
|
}
|
||||||
|
|
||||||
_hubConnection = new HubConnectionBuilder()
|
_hubConnection = new HubConnectionBuilder()
|
||||||
.WithUrl("https://govor-team-govor-88b3.twc1.net/api/chats", options =>
|
.WithUrl($"{baseUrl}/api/chats", options =>
|
||||||
{
|
{
|
||||||
options.AccessTokenProvider = () => Task.FromResult(AuthToken);
|
options.AccessTokenProvider = () => Task.FromResult(AuthToken);
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -8,4 +8,5 @@ public class FriendshipDto
|
|||||||
public Guid RequesterId { get; set; }
|
public Guid RequesterId { get; set; }
|
||||||
public Guid AddresseeId { get; set; }
|
public Guid AddresseeId { get; set; }
|
||||||
public FriendshipStatus Status { get; set; }
|
public FriendshipStatus Status { get; set; }
|
||||||
|
public UserDto Requester { get; set; }
|
||||||
}
|
}
|
||||||
Reference in New Issue
Block a user