Chat client

This commit is contained in:
Artemy
2025-06-19 19:42:42 +07:00
parent d18ad19f80
commit efcd970e90
5 changed files with 341 additions and 13 deletions
+98
View File
@@ -1,8 +1,106 @@
using System.Security.Claims;
using Govor.Core.Models;
using Govor.Core.Repositories.Users;
using Govor.Data.Repositories.Exceptions;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR;
namespace Govor.API.Hubs;
[Authorize]
public class ChatsHub : Hub
{
private readonly IUsersRepository _usersRepository;
private readonly ILogger<ChatsHub> _logger;
public ChatsHub(IUsersRepository usersRepository, ILogger<ChatsHub> logger)
{
_usersRepository = usersRepository;
_logger = logger;
}
public override async Task OnConnectedAsync()
{
var userId = GetUserId();
if (userId != Guid.Empty)
{
// Привязываем ConnectionId к UserId
await Groups.AddToGroupAsync(Context.ConnectionId, userId.ToString());
_logger.LogInformation("User {UserId} connected with ConnectionId {ConnectionId}", userId, Context.ConnectionId);
}
await base.OnConnectedAsync();
}
public override async Task OnDisconnectedAsync(Exception? exception)
{
var userId = GetUserId();
if (userId != Guid.Empty)
{
await Groups.RemoveFromGroupAsync(Context.ConnectionId, userId.ToString());
_logger.LogInformation("User {UserId} disconnected", userId);
}
await base.OnDisconnectedAsync(exception);
}
public async Task Send(string message, Guid toUserId)
{
// Валидация входных данных
if (string.IsNullOrWhiteSpace(message))
{
_logger.LogWarning("Empty message received from user {UserId}", GetUserId());
throw new ArgumentException("Message cannot be empty", nameof(message));
}
var senderId = GetUserId();
if (senderId == Guid.Empty)
{
_logger.LogError("Could not retrieve sender userId");
throw new InvalidOperationException("User not authenticated");
}
// Проверка существования получателя
try
{
await _usersRepository.FindByIdAsync(toUserId);
}
catch (NotFoundByKeyException<User> ex)
{
_logger.LogWarning("Recipient user {ToUserId} not found", toUserId);
throw;
}
catch (ArgumentException ex)
{
_logger.LogWarning("Invalid recipient userId received from user {UserId}", GetUserId());
throw;
}
try
{
_logger.LogInformation("Message sent from {SenderId} to {RecipientId}: {Message}", senderId, toUserId, message);
// Отправка сообщения отправителю и получателю
await Clients.Group(toUserId.ToString()).SendAsync("Receive", message, senderId);
await Clients.Group(senderId.ToString()).SendAsync("Receive", message, senderId);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error sending message from {SenderId} to {RecipientId}", senderId, toUserId);
throw;
}
}
private Guid GetUserId()
{
var userIdClaim = Context.User?.FindFirst("userID")?.Value;
_logger.LogInformation("Claims: {Claims}", string.Join(", ", Context.User?.Claims.Select(c => $"{c.Type}: {c.Value}") ?? new string[0]));
if (string.IsNullOrEmpty(userIdClaim))
{
_logger.LogError("No userID claim found");
return Guid.Empty;
}
return Guid.TryParse(userIdClaim, out var userId) ? userId : Guid.Empty;
}
}
+47 -5
View File
@@ -1,3 +1,5 @@
using System.Text;
using Govor.API.Hubs;
using Govor.API.Services;
using Govor.API.Services.Authentication;
using Govor.Core.Infrastructure.Extensions;
@@ -11,6 +13,7 @@ using Govor.Data.Repositories;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.IdentityModel.Tokens;
var builder = WebApplication.CreateBuilder(args);
@@ -18,14 +21,53 @@ var configuration = builder.Configuration;
var services = builder.Services;
builder.Configuration.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
builder.Services.AddCors(options =>
{
options.AddPolicy("AllowFrontend", policy =>
{
policy.WithOrigins("http://localhost:3000", "https://localhost:3000")
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials();
});
});
builder.Services.Configure<JwtOption>(configuration.GetSection(nameof(JwtOption)));
// Add services
builder.Services.AddSignalR();
builder.Services.AddAuthorization();
builder.Services.AddAuthentication("Bearer")
.AddJwtBearer();
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = false,
ValidateAudience = false,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes(builder.Configuration["JwtOption:SecretKeу"]!))
};
options.Events = new JwtBearerEvents
{
OnMessageReceived = context =>
{
var accessToken = context.Request.Query["access_token"];
var path = context.HttpContext.Request.Path;
if (!string.IsNullOrEmpty(accessToken) && path.StartsWithSegments("/api/chats"))
{
context.Token = accessToken;
}
return Task.CompletedTask;
}
};
});
builder.Services.AddAuthorization();
builder.Services.AddControllers();
@@ -66,8 +108,8 @@ app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.MapHub<ChatsHub>("/api/chats");
app.Map("/hello", [Authorize]() => "Hello World!");
app.Map("/", () => "Not for browser");
app.Map("/", () => "Not for browsers");
app.Run();
@@ -25,7 +25,8 @@ public class JwtService : IJwtService
SecurityAlgorithms.HmacSha256Signature);
var token = new JwtSecurityToken(signingCredentials: singing,
expires: DateTime.UtcNow.AddHours(_jwtOption.Hours));
expires: DateTime.UtcNow.AddHours(_jwtOption.Hours),
claims: claims);
return new JwtSecurityTokenHandler().WriteToken(token);
}