mirror of
https://github.com/Govor-team/Govor.git
synced 2026-07-21 11:44:56 +00:00
Implement user session management and JWT refresh tokens
Added user session models, interfaces, repository, and service for managing user sessions and refresh tokens. Refactored authentication flow to return user objects and open sessions with device info, supporting refresh token generation and validation. Updated JWT configuration to separate access and refresh options, and refactored related tests and API contracts. Improved media upload handling and error logging. Migrated dependency references and DI registrations accordingly.
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
using Govor.API.Services.AdminsStuff.Interfaces;
|
||||
using Govor.Application.Interfaces;
|
||||
using Govor.Contracts.DTOs;
|
||||
using Govor.Contracts.Requests;
|
||||
using Govor.Core.Repositories.Invaites;
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
using Govor.API.Services.AdminsStuff.Interfaces;
|
||||
using Govor.Application.Interfaces;
|
||||
using Govor.Contracts.Responses.Admins;
|
||||
using Govor.Core.Models.Users;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
using Govor.API.Services.Authentication.Interfaces;
|
||||
using Govor.Application.Exceptions.AuthService;
|
||||
using Govor.Application.Exceptions.InvitesService;
|
||||
using Govor.Application.Interfaces.Authentication;
|
||||
using Govor.Application.Interfaces.UserSession;
|
||||
using Govor.Contracts.Requests;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
@@ -13,33 +13,38 @@ namespace Govor.API.Controllers;
|
||||
[Route("api/[controller]")]
|
||||
public class AuthController : Controller
|
||||
{
|
||||
private IUserSessionOpener _userSession;
|
||||
private IInvitesService _invitesService;
|
||||
private IAccountService _accountService;
|
||||
private ILogger<AuthController> _logger;
|
||||
|
||||
public AuthController(IAccountService accountService, IInvitesService invitesService, ILogger<AuthController> logger)
|
||||
public AuthController(IAccountService accountService, IInvitesService invitesService,IUserSessionOpener userSessionOpener, ILogger<AuthController> logger)
|
||||
{
|
||||
_userSession = userSessionOpener;
|
||||
_accountService = accountService;
|
||||
_invitesService = invitesService;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
[RequireHttps]
|
||||
[HttpPost("register")]// api/auth/register
|
||||
//[RequireHttps]
|
||||
public async Task<IActionResult> Register([FromBody] RegistrationRequest registrationRequest)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return BadRequest(ModelState);
|
||||
}
|
||||
|
||||
var invite = await _invitesService.ValidateAsync(registrationRequest.InviteLink);
|
||||
|
||||
var token = await _accountService.RegistrationAsync(registrationRequest.Name, registrationRequest.Password,
|
||||
var user = await _accountService.RegistrationAsync(registrationRequest.Name, registrationRequest.Password,
|
||||
invite);
|
||||
_logger.LogInformation($"Register request for {registrationRequest.Name} processed successfully");
|
||||
|
||||
_logger.LogInformation($"Register request for {user.Username} with id {user.Id} processed successfully");
|
||||
|
||||
var token = await _userSession.OpenSessionAsync(user, registrationRequest.DeviceInfo);
|
||||
|
||||
_logger.LogInformation($"Session for user {user.Username} with id {user.Id} has been opened");
|
||||
return Ok(new { token });
|
||||
}
|
||||
catch (UserAlreadyExistException ex)
|
||||
@@ -64,35 +69,73 @@ public class AuthController : Controller
|
||||
}
|
||||
}
|
||||
|
||||
[RequireHttps]
|
||||
[HttpPost("login")]// api/auth/login
|
||||
//[RequireHttps]
|
||||
public async Task<IActionResult> Login([FromBody] LoginRequest userRequest)
|
||||
public async Task<IActionResult> Login([FromBody] LoginRequest loginRequest)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return BadRequest(ModelState);
|
||||
}
|
||||
|
||||
var token = await _accountService.LoginAsync(userRequest.Name, userRequest.Password);
|
||||
_logger.LogInformation($"Login request for {userRequest.Name} processed successfully");
|
||||
var user = await _accountService.LoginAsync(loginRequest.Name, loginRequest.Password);
|
||||
_logger.LogInformation($"Login request for {user.Username} with id {user.Id} processed successfully");
|
||||
|
||||
var token = await _userSession.OpenSessionAsync(user, loginRequest.DeviceInfo);
|
||||
|
||||
_logger.LogInformation($"Session for user {user.Username} with id {user.Id} has been opened");
|
||||
|
||||
return Ok(new { token });
|
||||
}
|
||||
catch (UserNotRegisteredException ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "Login failed for user {Name}", userRequest.Name);
|
||||
_logger.LogWarning(ex, "Login failed for user {Name}", loginRequest.Name);
|
||||
return BadRequest("Login failed: user does not exist.");
|
||||
}
|
||||
catch (LoginUserException ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "Login failed for user {Name}", userRequest.Name);
|
||||
_logger.LogWarning(ex, "Login failed for user {Name}", loginRequest.Name);
|
||||
return BadRequest("Login failed: username or password is incorrect.");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Unexpected error during login for user {Name}", userRequest.Name);
|
||||
_logger.LogError(ex, "Unexpected error during login for user {Name}", loginRequest.Name);
|
||||
return StatusCode(500, "An unexpected error occurred. Please try again later.");
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
[RequireHttps]
|
||||
[HttpPost("refresh")]
|
||||
public async Task<IActionResult> Refresh([FromBody] string refreshToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
return BadRequest(ModelState);
|
||||
|
||||
if (string.IsNullOrEmpty(refreshToken))
|
||||
throw new InvalidOperationException("Refresh token cant be empty.");
|
||||
|
||||
var newAccessToken = await _accountService.RefreshTokenAsync(refreshToken);
|
||||
return Ok(new { accessToken = newAccessToken });
|
||||
}
|
||||
catch (InvalidOperationException ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "Invalid refresh token");
|
||||
return BadRequest(ex.Message);
|
||||
}
|
||||
catch (UnauthorizedAccessException ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "Refresh token failed");
|
||||
return Unauthorized("Invalid refresh token");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, ex.Message);
|
||||
return StatusCode(500, "An unexpected error occurred.");
|
||||
}
|
||||
}
|
||||
*/
|
||||
|
||||
}
|
||||
@@ -32,7 +32,7 @@ public class ChatLoadController : Controller
|
||||
public async Task<IActionResult> GetChatMessages(
|
||||
[FromQuery] Guid chatId,
|
||||
[FromQuery] Guid? startMessageId,
|
||||
[FromQuery] int pageSize = 20)
|
||||
[FromQuery] int pageSize)
|
||||
{
|
||||
try
|
||||
{
|
||||
|
||||
@@ -29,32 +29,51 @@ public class MediaController : Controller
|
||||
}
|
||||
|
||||
[HttpPost("upload")]
|
||||
[RequestSizeLimit(100_000_000)] // ~100MB
|
||||
[RequestSizeLimit(20_000_000)] // ~20MB
|
||||
public async Task<IActionResult> Upload([FromForm] MediaUploadRequest request)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (request.FromFile.Length > 20_000_000)
|
||||
return BadRequest("File is too large");
|
||||
|
||||
if (!ModelState.IsValid)
|
||||
return BadRequest(ModelState);
|
||||
|
||||
// Чтение байт из IFormFile
|
||||
using var memoryStream = new MemoryStream();
|
||||
await request.Data.CopyToAsync(memoryStream);
|
||||
|
||||
await request.FromFile.CopyToAsync(memoryStream);
|
||||
|
||||
byte[] fileBytes = memoryStream.ToArray();
|
||||
|
||||
var media = new Media(
|
||||
_currentUserService.GetCurrentUserId(),
|
||||
DateTime.UtcNow,
|
||||
Path.GetFileName(request.FromFile.FileName),
|
||||
fileBytes,
|
||||
request.FileName,
|
||||
request.Type,
|
||||
request.MimeType,
|
||||
request.EncryptedKey
|
||||
);
|
||||
|
||||
var result = await _mediaService.UploadMediaAsync(media);
|
||||
|
||||
_logger.LogInformation(
|
||||
$"Uploaded file: {Path.GetFileName(request.FromFile.FileName)} from user {_currentUserService.GetCurrentUserId()}");
|
||||
|
||||
return Ok(result);
|
||||
}
|
||||
catch (InvalidOperationException ex)
|
||||
{
|
||||
_logger.LogWarning(ex, ex.Message);
|
||||
return BadRequest(ex.Message);
|
||||
}
|
||||
catch (UnauthorizedAccessException ex)
|
||||
{
|
||||
_logger.LogWarning(ex, ex.Message);
|
||||
return Unauthorized(ex.Message);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error uploading media");
|
||||
@@ -71,7 +90,12 @@ public class MediaController : Controller
|
||||
return BadRequest(ModelState);
|
||||
|
||||
var media = await _mediaService.GetMediaByIdAsync(id);
|
||||
return File(media.Data, media.MineType, media.FileName);
|
||||
return File(media.Data, media.MineType, Path.GetFileName(media.FileName));
|
||||
}
|
||||
catch (KeyNotFoundException ex)
|
||||
{
|
||||
_logger.LogWarning(ex, ex.Message);
|
||||
return NotFound(ex.Message);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
|
||||
Reference in New Issue
Block a user