using System.Text.Json; using Application.Endpoints; using Application.Services.Jwt; namespace API.Middlewares; public class JwtMiddleware { private readonly IJwtService _jwtService; private readonly RequestDelegate _next; private readonly ILogger _logger; public JwtMiddleware(RequestDelegate next, IJwtService jwtService, ILogger logger) { _next = next; _jwtService = jwtService; _logger = logger; } public async Task Invoke(HttpContext context) { var path = context.Request.Path.ToString().ToLower(); var bypassPaths = new[] { "/api/authorization/login", "/api/doctors/register", "/api/patients/register", "/api/authorization/reset_password" }; if (bypassPaths.Contains(path)) { await _next(context); } else { var token = context.Request.Headers.Authorization.FirstOrDefault()?.Split(" ").Last(); _logger.LogInformation(token); if (token != null && _jwtService.ValidateJwtToken(token)) { await _next(context); } else { context.Response.StatusCode = StatusCodes.Status401Unauthorized; context.Response.ContentType = "application/json"; var response = new BaseResponse { StatusCode = StatusCodes.Status401Unauthorized, Message = "Invalid JWT Token", Data = null }; var responseJson = JsonSerializer.Serialize(response); await context.Response.WriteAsync(responseJson); } } } }