/
egopen
/
Lab1
Обзор
Документация
Войти
/
egopen
/
Lab1
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
Lab4/library/Controllers/BooksController .cs
246 строк
9 KB
Egopen
lab 4
01 ноя 2025, 18:03
01 ноя 2025, 18:03
78d017c
Код
Авторство
О чём код?
using library.DB.Models; using library.DTO; using library.QueueMessages; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.OpenApi.Models; using RabbitMQ.Client; using System.Text; using System.Text.Json; namespace library.Controllers.v1 { [ApiController] [Route("api/v1/[controller]")] public class BooksController : ControllerBase { private readonly IChannel _channel; public BooksController(IConnection rabbitConnection) { _channel = rabbitConnection.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(); } [HttpGet("{bookId}")] [ProducesResponseType(typeof(Book), 200)] [ProducesResponseType(typeof(OpenApiError), 404)] [ProducesResponseType(typeof(OpenApiError), 500)] public async Task<IActionResult> GetBook(Guid bookId) { var message = new BaseMessage { Id = Guid.NewGuid(), Version = "v1", Action = "get_book", Data = new { BookId = bookId } }; var props = new BasicProperties(); props.ContentType = "application/json"; props.MessageId = message.Id.ToString(); var messageBytes = Encoding.UTF8.GetBytes(JsonSerializer.Serialize(message)); await _channel.BasicPublishAsync("Books", "get_book.request", true, props, messageBytes); return Accepted(new { message = "Get book request sent", requestId = message.Id }); } [HttpGet] [ProducesResponseType(typeof(IEnumerable<Book>), 200)] [ProducesResponseType(typeof(OpenApiError), 404)] [ProducesResponseType(typeof(OpenApiError), 500)] public async Task<IActionResult> GetBooks([FromQuery] int page = 1, [FromQuery] int pageSize = 20, [FromQuery] string include = "") { var includeFields = include.Split(',', StringSplitOptions.RemoveEmptyEntries); bool withAuthor = includeFields.Contains("author"); var message = new BaseMessage { Id = Guid.NewGuid(), Version = "v1", Action = "get_books", Data = new { Page = page, PageSize = pageSize, WithAuthor = withAuthor } }; var props = new BasicProperties(); props.ContentType = "application/json"; props.MessageId = message.Id.ToString(); var messageBytes = Encoding.UTF8.GetBytes(JsonSerializer.Serialize(message)); await _channel.BasicPublishAsync("Books", "get_books.request", true, props, messageBytes); return Accepted(new { message = "Get books request sent", requestId = message.Id }); } [HttpPost] [Authorize(Roles = "Admin,Moderator")] [ProducesResponseType(typeof(Book), 200)] [ProducesResponseType(typeof(OpenApiError), 404)] [ProducesResponseType(typeof(OpenApiError), 500)] public async Task<IActionResult> AddBook([FromBody] AddBookRequest request) { if (!ModelState.IsValid) { return BadRequest(ModelState); } var token = GetAuthToken(); var message = new BaseMessage { Id = Guid.NewGuid(), Version = "v1", Action = "add_book", AuthKey = token, Data = new { request.AuthorId, request.Title, request.CreationDate } }; var props = new BasicProperties(); props.ContentType = "application/json"; props.MessageId = message.Id.ToString(); var messageBytes = Encoding.UTF8.GetBytes(JsonSerializer.Serialize(message)); await _channel.BasicPublishAsync("Books", "add_book.request", true, props, messageBytes); return Accepted(new { message = "Add book request sent", requestId = message.Id }); } [HttpDelete("{bookId}")] [Authorize(Roles = "Admin,Moderator")] [ProducesResponseType(typeof(object), 200)] [ProducesResponseType(typeof(OpenApiError), 404)] [ProducesResponseType(typeof(OpenApiError), 500)] public async Task<IActionResult> DeleteBook(Guid bookId) { var token = GetAuthToken(); var message = new BaseMessage { Id = Guid.NewGuid(), Version = "v1", Action = "delete_book", AuthKey = token, Data = new { BookId = bookId } }; var props = new BasicProperties(); props.ContentType = "application/json"; props.MessageId = message.Id.ToString(); var messageBytes = Encoding.UTF8.GetBytes(JsonSerializer.Serialize(message)); await _channel.BasicPublishAsync("Books", "delete_book.request", true, props, messageBytes); return Accepted(new { message = "Delete book request sent", requestId = message.Id }); } [HttpGet("authors/{authorId}")] [ProducesResponseType(typeof(Author), 200)] [ProducesResponseType(typeof(OpenApiError), 404)] [ProducesResponseType(typeof(OpenApiError), 500)] public async Task<IActionResult> GetAuthor(Guid authorId) { var message = new BaseMessage { Id = Guid.NewGuid(), Version = "v1", Action = "get_author", Data = new { AuthorId = authorId } }; var props = new BasicProperties(); props.ContentType = "application/json"; props.MessageId = message.Id.ToString(); var messageBytes = Encoding.UTF8.GetBytes(JsonSerializer.Serialize(message)); await _channel.BasicPublishAsync("Books", "get_author.request", true, props, messageBytes); return Accepted(new { message = "Get author request sent", requestId = message.Id }); } [HttpPost("authors")] [Authorize(Roles = "Admin,Moderator")] [ProducesResponseType(typeof(Author), 200)] [ProducesResponseType(typeof(OpenApiError), 404)] public async Task<IActionResult> AddAuthor([FromBody] AddAuthorRequest request) { if (!ModelState.IsValid) { return BadRequest(ModelState); } var token = GetAuthToken(); var message = new BaseMessage { Id = Guid.NewGuid(), Version = "1", Action = "add_author", AuthKey = token, Data = new { request.Name, request.BirthDate } }; var props = new BasicProperties(); props.ContentType = "application/json"; props.MessageId = message.Id.ToString(); var messageBytes = Encoding.UTF8.GetBytes(JsonSerializer.Serialize(message)); await _channel.BasicPublishAsync("Books", "add_author.request", true, props, messageBytes); return Accepted(new { message = "Add author request sent", requestId = message.Id }); } [HttpDelete("authors/{authorId}")] [ProducesResponseType(typeof(object), 200)] [ProducesResponseType(typeof(OpenApiError), 404)] [ProducesResponseType(typeof(OpenApiError), 500)] [Authorize(Roles = "Admin")] public async Task<IActionResult> DeleteAuthor(Guid authorId) { var token = GetAuthToken(); var message = new BaseMessage { Id = Guid.NewGuid(), Version = "v1", Action = "delete_author", AuthKey = token, Data = new { AuthorId = authorId } }; var props = new BasicProperties(); props.ContentType = "application/json"; props.MessageId = message.Id.ToString(); var messageBytes = Encoding.UTF8.GetBytes(JsonSerializer.Serialize(message)); await _channel.BasicPublishAsync("Books", "delete_author.request",true, props, messageBytes); return Accepted(new { message = "Delete author request sent", requestId = message.Id }); } } }