53 lines
1.6 KiB
C#
53 lines
1.6 KiB
C#
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;
|
|
|
|
public JwtMiddleware(RequestDelegate next, IJwtService jwtService)
|
|
{
|
|
_next = next;
|
|
_jwtService = jwtService;
|
|
}
|
|
|
|
public async Task Invoke(HttpContext context)
|
|
{
|
|
var path = context.Request.Path.ToString().ToLower();
|
|
|
|
// Define the paths that should bypass JWT validation
|
|
var bypassPaths = new[]
|
|
{
|
|
"/api/doctors/login",
|
|
"/api/doctors/register",
|
|
"/api/patients/login",
|
|
"/api/patients/register"
|
|
};
|
|
|
|
if (!bypassPaths.Contains(path))
|
|
{
|
|
var token = context.Request.Headers["Authorization"].FirstOrDefault()?.Split(" ").Last();
|
|
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);
|
|
}
|
|
}
|
|
}
|
|
} |