/
egopen
/
Lab1
Обзор
Документация
Войти
/
egopen
/
Lab1
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
Lab4/library/Controllers/UsersController .cs
217 строк
7 KB
Egopen
lab 4
01 ноя 2025, 18:03
01 ноя 2025, 18:03
78d017c
Код
Авторство
О чём код?
using library.DB.Models; using library.QueueMessages; using library.Services; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.OpenApi.Models; using RabbitMQ.Client; using System.ComponentModel.DataAnnotations; using System.Text; using System.Text.Json; namespace library.Controllers { [ApiController] [Route("api/[controller]")] [Authorize] public class UsersController : ControllerBase { private readonly TokenService _tokenService; private readonly IChannel _channel; public UsersController(TokenService tokenService, IConnection rabbit) { _tokenService = tokenService; _channel = rabbit.CreateChannelAsync().GetAwaiter().GetResult(); } private string GetAuthToken() { var authHeader = Request.Headers["Authorization"].FirstOrDefault(); if (string.IsNullOrEmpty(authHeader) || !authHeader.StartsWith("Bearer ")) throw new UnauthorizedAccessException("Authorization header is required"); return authHeader.Substring("Bearer ".Length).Trim(); } /// <summary> /// Универсальный метод с ретраями для отправки в RabbitMQ /// </summary> private async Task PublishWithRetryAsync( string exchange, string routingKey, bool mandatory, BasicProperties props, byte[] body, int maxRetries = 3, int delayMs = 500) { int attempt = 0; while (true) { try { await _channel.BasicPublishAsync(exchange, routingKey, mandatory, props, body); break; } catch (Exception ex) when (attempt < maxRetries) { attempt++; Console.WriteLine($"[Retry {attempt}/{maxRetries}] Failed to publish to RabbitMQ: {ex.Message}"); await Task.Delay(delayMs); } } } [HttpGet("me")] [ProducesResponseType(typeof(User), 200)] [ProducesResponseType(typeof(OpenApiError), 404)] [ProducesResponseType(typeof(OpenApiError), 500)] public async Task<IActionResult> GetCurrentUser() { var token = GetAuthToken(); var message = new BaseMessage { Id = Guid.NewGuid(), Version = "v1", Action = "get_current", AuthKey = token, Data = new { } }; var props = new BasicProperties { ContentType = "application/json", MessageId = message.Id.ToString() }; var body = Encoding.UTF8.GetBytes(JsonSerializer.Serialize(message)); await PublishWithRetryAsync("Users", "get_current.request", true, props, body); return Accepted(new { message = "Get current user request sent", requestId = message.Id }); } [HttpGet("{userId}")] [Authorize(Roles = "Admin")] [ProducesResponseType(typeof(User), 200)] [ProducesResponseType(typeof(OpenApiError), 404)] [ProducesResponseType(typeof(OpenApiError), 500)] public async Task<IActionResult> GetUserById(Guid userId) { var token = GetAuthToken(); var message = new BaseMessage { Id = Guid.NewGuid(), Version = "v1", Action = "get_by_id", AuthKey = token, Data = new { UserId = userId } }; var props = new BasicProperties { ContentType = "application/json", MessageId = message.Id.ToString() }; var body = Encoding.UTF8.GetBytes(JsonSerializer.Serialize(message)); await PublishWithRetryAsync("Users", "get_by_id.request", true, props, body); return Accepted(new { message = "Get user by id request sent", requestId = message.Id }); } [HttpGet] [Authorize(Roles = "Admin")] [ProducesResponseType(typeof(IEnumerable<User>), 200)] [ProducesResponseType(typeof(OpenApiError), 404)] [ProducesResponseType(typeof(OpenApiError), 500)] public async Task<IActionResult> GetAllUsers([FromQuery] int page = 1, [FromQuery] int pageSize = 20) { var token = GetAuthToken(); var message = new BaseMessage { Id = Guid.NewGuid(), Version = "v1", Action = "get_all", AuthKey = token, Data = new { Page = page, PageSize = pageSize } }; var props = new BasicProperties { ContentType = "application/json", MessageId = message.Id.ToString() }; var body = Encoding.UTF8.GetBytes(JsonSerializer.Serialize(message)); await PublishWithRetryAsync("Users", "get_all.request", true, props, body); return Accepted(new { message = "Get all users request sent", requestId = message.Id }); } [HttpDelete("{userId}")] [Authorize(Roles = "Admin")] [ProducesResponseType(typeof(object), 200)] [ProducesResponseType(typeof(OpenApiError), 404)] [ProducesResponseType(typeof(OpenApiError), 500)] public async Task<IActionResult> DeleteUser(Guid userId) { var token = GetAuthToken(); var message = new BaseMessage { Id = Guid.NewGuid(), Version = "v1", Action = "delete", AuthKey = token, Data = new { UserId = userId } }; var props = new BasicProperties { ContentType = "application/json", MessageId = message.Id.ToString() }; var body = Encoding.UTF8.GetBytes(JsonSerializer.Serialize(message)); await PublishWithRetryAsync("Users", "delete.request", true, props, body); return Accepted(new { message = "Delete user request sent", requestId = message.Id }); } [HttpGet("internal/user/{userId}")] [ProducesResponseType(typeof(object), 200)] [ProducesResponseType(typeof(UnauthorizedResult), 401)] [ProducesResponseType(typeof(NotFoundResult), 404)] public async Task<IActionResult> GetUserInternal(Guid userId, [FromHeader] string internalKey = "") { var message = new BaseMessage { Id = Guid.NewGuid(), Version = "v1", Action = "internal_get", AuthKey = internalKey, Data = new { UserId = userId } }; var props = new BasicProperties { ContentType = "application/json", MessageId = message.Id.ToString() }; var body = Encoding.UTF8.GetBytes(JsonSerializer.Serialize(message)); await PublishWithRetryAsync("Users", "internal_get.request", true, props, body); return Accepted(new { message = "Internal get user request sent", requestId = message.Id }); } } }