Adding chat system

This commit is contained in:
hz
2025-06-05 09:06:32 -05:00
parent 4f1342e0af
commit ea25e3b63d
6 changed files with 159 additions and 0 deletions
+47
View File
@@ -0,0 +1,47 @@
using GameAuthApi.Models;
using GameAuthApi.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
using System.Threading.Tasks;
namespace GameAuthApi.Controllers;
[ApiController]
[Route("api/[controller]")]
public class ChatController : ControllerBase
{
private readonly ChatService _chatService;
public ChatController(ChatService chatService)
{
_chatService = chatService;
}
[HttpPost("send")]
[Authorize(Roles = "USER,SUPER")]
public async Task<IActionResult> Send([FromBody] ChatMessageRequest req)
{
if (string.IsNullOrWhiteSpace(req.Content))
return BadRequest("Content required");
var senderId = User.FindFirstValue(ClaimTypes.NameIdentifier);
var msg = new ChatMessage
{
SenderId = senderId,
Content = req.Content
};
await _chatService.CreateAsync(msg);
return Ok(msg);
}
[HttpGet("recent")]
[Authorize(Roles = "USER,SUPER")]
public async Task<IActionResult> Recent([FromQuery] int count = 10)
{
if (count <= 0)
count = 10;
var messages = await _chatService.GetRecentAsync(count);
return Ok(messages);
}
}
+58
View File
@@ -0,0 +1,58 @@
using GameAuthApi.Controllers;
using GameAuthApi.Models;
using GameAuthApi.Services;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using System.Security.Claims;
public class ChatControllerTests
{
private static IConfiguration cfg = new ConfigurationBuilder()
.AddInMemoryCollection(new Dictionary<string,string>
{
{"MongoDB:ConnectionString","mongodb://localhost"},
{"MongoDB:DatabaseName","test"}
}).Build();
private static ControllerContext ContextWithUser(string id)
{
var ctx = new DefaultHttpContext();
ctx.User = new ClaimsPrincipal(new ClaimsIdentity(new[]
{
new Claim(ClaimTypes.NameIdentifier,id)
}, "mock"));
return new ControllerContext { HttpContext = ctx };
}
[Fact]
public async Task Send_EmptyContent_ReturnsBadRequest()
{
var svc = new Mock<ChatService>(cfg);
var controller = new ChatController(svc.Object)
{
ControllerContext = ContextWithUser("u")
};
var result = await controller.Send(new ChatMessageRequest { Content = "" });
Assert.IsType<BadRequestObjectResult>(result);
}
[Fact]
public async Task Recent_ReturnsOk()
{
var list = new List<ChatMessage>();
var svc = new Mock<ChatService>(cfg);
svc.Setup(s => s.GetRecentAsync(5)).ReturnsAsync(list);
var controller = new ChatController(svc.Object)
{
ControllerContext = ContextWithUser("u")
};
var result = await controller.Recent(5);
var ok = Assert.IsType<OkObjectResult>(result);
Assert.Equal(list, ok.Value);
}
}
+19
View File
@@ -0,0 +1,19 @@
using System;
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
namespace GameAuthApi.Models;
public class ChatMessage
{
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }
[BsonRepresentation(BsonType.ObjectId)]
public string SenderId { get; set; }
public string Content { get; set; }
public DateTime Timestamp { get; set; } = DateTime.UtcNow;
}
+6
View File
@@ -0,0 +1,6 @@
namespace GameAuthApi.Models;
public class ChatMessageRequest
{
public string Content { get; set; }
}
+1
View File
@@ -53,6 +53,7 @@ builder.Services.AddSingleton<SpawnableService>();
builder.Services.AddSingleton<ItemService>();
builder.Services.AddSingleton<BlacklistService>();
builder.Services.AddSingleton<AuctionService>();
builder.Services.AddSingleton<ChatService>();
var jwtKey = builder.Configuration["Jwt:Key"];
var keyBytes = Encoding.UTF8.GetBytes(jwtKey);
+28
View File
@@ -0,0 +1,28 @@
using System.Collections.Generic;
using System.Threading.Tasks;
using GameAuthApi.Models;
using Microsoft.Extensions.Configuration;
using MongoDB.Driver;
namespace GameAuthApi.Services;
public class ChatService
{
private readonly IMongoCollection<ChatMessage> _messages;
public ChatService(IConfiguration config)
{
var client = new MongoClient(config["MongoDB:ConnectionString"]);
var db = client.GetDatabase(config["MongoDB:DatabaseName"]);
_messages = db.GetCollection<ChatMessage>("ChatMessages");
}
public virtual async Task CreateAsync(ChatMessage msg) =>
await _messages.InsertOneAsync(msg);
public virtual async Task<List<ChatMessage>> GetRecentAsync(int count) =>
await _messages.Find(_ => true)
.SortByDescending(m => m.Timestamp)
.Limit(count)
.ToListAsync();
}