mirror of
https://github.com/RedWizardsLab/EchoHub.git
synced 2026-09-04 08:36:11 +02:00
feat: Refactor authentication and token management
- Updated EchoHubConnection to use ApiClient for token retrieval. - Introduced ValidationConstants for common validation patterns and limits. - Enhanced AuthDtos with refresh token support and expiration details. - Added new ChatDtos for channel creation and topic updates. - Created CommonDtos for error and paginated responses. - Implemented RefreshToken model for managing refresh tokens. - Modified JwtTokenService to generate and hash refresh tokens. - Updated AuthController to handle registration, login, token refresh, and logout with improved error handling. - Enhanced ChannelsController with channel creation, topic updates, and pagination for channel retrieval. - Added FilesController for file management with rate limiting. - Improved UsersController for profile updates and avatar uploads with validation. - Integrated rate limiting across controllers to manage request load. - Introduced FileValidationHelper for validating uploaded image files. - Updated database context to include RefreshToken and enforce unique constraints. - Enhanced ChatHub for improved channel and message handling with validation. - Updated Program.cs to configure rate limiting and CORS policies.
This commit is contained in:
@@ -5,12 +5,15 @@ using EchoHub.Server.Data;
|
||||
using EchoHub.Server.Services;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.RateLimiting;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace EchoHub.Server.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/users")]
|
||||
[Authorize]
|
||||
[EnableRateLimiting("general")]
|
||||
public class UsersController(EchoHubDbContext db, ImageToAsciiService asciiService) : ControllerBase
|
||||
{
|
||||
[HttpGet("{username}/profile")]
|
||||
@@ -20,33 +23,45 @@ public class UsersController(EchoHubDbContext db, ImageToAsciiService asciiServi
|
||||
var user = await db.Users.FirstOrDefaultAsync(u => u.Username == normalizedUsername);
|
||||
|
||||
if (user is null)
|
||||
return NotFound(new { Error = "User not found." });
|
||||
return NotFound(new ErrorResponse("User not found."));
|
||||
|
||||
return Ok(ToProfileDto(user));
|
||||
}
|
||||
|
||||
[HttpPut("profile")]
|
||||
[Authorize]
|
||||
public async Task<IActionResult> UpdateProfile([FromBody] UpdateProfileRequest request)
|
||||
{
|
||||
var userIdClaim = User.FindFirstValue(ClaimTypes.NameIdentifier);
|
||||
if (userIdClaim is null)
|
||||
return Unauthorized();
|
||||
return Unauthorized(new ErrorResponse("Authentication required."));
|
||||
|
||||
var userId = Guid.Parse(userIdClaim);
|
||||
var user = await db.Users.FindAsync(userId);
|
||||
|
||||
if (user is null)
|
||||
return NotFound(new { Error = "User not found." });
|
||||
return NotFound(new ErrorResponse("User not found."));
|
||||
|
||||
if (request.DisplayName is not null)
|
||||
{
|
||||
if (request.DisplayName.Length > ValidationConstants.MaxDisplayNameLength)
|
||||
return BadRequest(new ErrorResponse($"Display name must not exceed {ValidationConstants.MaxDisplayNameLength} characters."));
|
||||
user.DisplayName = request.DisplayName.Trim();
|
||||
}
|
||||
|
||||
if (request.Bio is not null)
|
||||
{
|
||||
if (request.Bio.Length > ValidationConstants.MaxBioLength)
|
||||
return BadRequest(new ErrorResponse($"Bio must not exceed {ValidationConstants.MaxBioLength} characters."));
|
||||
user.Bio = request.Bio.Trim();
|
||||
}
|
||||
|
||||
if (request.NicknameColor is not null)
|
||||
user.NicknameColor = request.NicknameColor.Trim();
|
||||
{
|
||||
var color = request.NicknameColor.Trim();
|
||||
if (color.Length > 0 && !ValidationConstants.HexColorRegex().IsMatch(color))
|
||||
return BadRequest(new ErrorResponse("Nickname color must be a valid hex color (e.g. #FF5500)."));
|
||||
user.NicknameColor = color.Length > 0 ? color : null;
|
||||
}
|
||||
|
||||
await db.SaveChangesAsync();
|
||||
|
||||
@@ -54,34 +69,38 @@ public class UsersController(EchoHubDbContext db, ImageToAsciiService asciiServi
|
||||
}
|
||||
|
||||
[HttpPost("avatar")]
|
||||
[Authorize]
|
||||
[EnableRateLimiting("upload")]
|
||||
public async Task<IActionResult> UploadAvatar()
|
||||
{
|
||||
var userIdClaim = User.FindFirstValue(ClaimTypes.NameIdentifier);
|
||||
if (userIdClaim is null)
|
||||
return Unauthorized();
|
||||
return Unauthorized(new ErrorResponse("Authentication required."));
|
||||
|
||||
var userId = Guid.Parse(userIdClaim);
|
||||
var user = await db.Users.FindAsync(userId);
|
||||
|
||||
if (user is null)
|
||||
return NotFound(new { Error = "User not found." });
|
||||
return NotFound(new ErrorResponse("User not found."));
|
||||
|
||||
if (!Request.HasFormContentType || Request.Form.Files.Count == 0)
|
||||
return BadRequest(new { Error = "No file uploaded." });
|
||||
return BadRequest(new ErrorResponse("No file uploaded."));
|
||||
|
||||
var file = Request.Form.Files[0];
|
||||
|
||||
if (file.Length > HubConstants.MaxAvatarSizeBytes)
|
||||
return BadRequest(new { Error = $"File size exceeds maximum of {HubConstants.MaxAvatarSizeBytes / (1024 * 1024)} MB." });
|
||||
return BadRequest(new ErrorResponse($"File size exceeds maximum of {HubConstants.MaxAvatarSizeBytes / (1024 * 1024)} MB."));
|
||||
|
||||
using var stream = file.OpenReadStream();
|
||||
|
||||
if (!FileValidationHelper.IsValidImage(stream))
|
||||
return BadRequest(new ErrorResponse("File is not a valid image. Supported formats: JPEG, PNG, GIF, WebP."));
|
||||
|
||||
var asciiArt = asciiService.ConvertToAscii(stream);
|
||||
|
||||
user.AvatarAscii = asciiArt;
|
||||
await db.SaveChangesAsync();
|
||||
|
||||
return Ok(new { AvatarAscii = asciiArt });
|
||||
return Ok(new AvatarUploadResponse(asciiArt));
|
||||
}
|
||||
|
||||
private static UserProfileDto ToProfileDto(Core.Models.User user) => new(
|
||||
|
||||
Reference in New Issue
Block a user