/
Extrap
/
Network_technologies_Project
Обзор
Документация
Войти
/
Extrap
/
Network_technologies_Project
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
Project/Controllers/ReportsController.cs
105 строк
4 KB
Extrap
Конечка (хз, но для воскресенья да)
21 дек 2025, 22:48
21 дек 2025, 22:48
1c6535d
Код
Авторство
О чём код?
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Project.Models.DTOs; using Project.Services; using System.Security.Claims; using System.IdentityModel.Tokens.Jwt; namespace Project.Controllers { [ApiController] [Route("api/[controller]")] [Authorize] public class ReportsController : ControllerBase { private readonly ReportService _reportService; public ReportsController(ReportService reportService) { _reportService = reportService; } [HttpPost("period")] public async Task<IActionResult> GetReportByPeriod([FromBody] ReportRequestDTO request) { if (request.StartDate > request.EndDate) return BadRequest("Start date cannot be after end date"); if (request.EndDate > DateTime.UtcNow) return BadRequest("End date cannot be in the future"); if (request.EndDate - request.StartDate > TimeSpan.FromDays(365)) return BadRequest("Period cannot exceed one year"); try { var userId = GetUserId(); var report = await _reportService.GenerateReportAsync(userId, request); return Ok(report); } catch (InvalidOperationException ex) { return NotFound(new { message = ex.Message }); } catch (Exception ex) { return StatusCode(500, new { message = $"Internal server error: {ex.Message}" }); } } [HttpGet("last-week")] public async Task<IActionResult> GetLastWeekReport() { try { var userId = GetUserId(); var endDate = DateTime.UtcNow; var startDate = endDate.AddDays(-7); var report = await _reportService.GenerateReportAsync(userId, startDate, endDate); return Ok(report); } catch (InvalidOperationException ex) { return NotFound(new { message = ex.Message }); } } [HttpGet("last-month")] public async Task<IActionResult> GetLastMonthReport() { try { var userId = GetUserId(); var endDate = DateTime.UtcNow; var startDate = endDate.AddMonths(-1); var report = await _reportService.GenerateReportAsync(userId, startDate, endDate); return Ok(report); } catch (InvalidOperationException ex) { return NotFound(new { message = ex.Message }); } } // Для получения ID private Guid GetUserId() { // Пытаемся найти ID в разных стандартных полях var idClaim = User.FindFirst(ClaimTypes.NameIdentifier)?.Value ?? User.FindFirst(JwtRegisteredClaimNames.Sub)?.Value ?? User.FindFirst("sub")?.Value ?? User.FindFirst("id")?.Value; // Пытаемся распарсить GUID if (Guid.TryParse(idClaim, out var userId)) { return userId; } // Если ничего не нашли или формат неверный — кидаем исключение, которое будет поймано middleware или вернет 500 throw new UnauthorizedAccessException("User ID not found or invalid in token"); } } }