Files
FACULTATE-HEALTHCARE_MANAGER/backend/API/Middlewares/JwtMiddleware.cs
T
2024-05-02 11:11:12 +00:00

56 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();
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();
Console.WriteLine(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);
}
}
}
}