| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869 |
- using Common.Extension;
- namespace Kitty_Fall.Website.Helpers;
- public class LoginRequiredMiddleware
- {
- private readonly RequestDelegate _next;
- public LoginRequiredMiddleware(RequestDelegate next)
- {
- _next = next;
- }
- public async Task InvokeAsync(HttpContext context)
- {
- if (ShouldSkip(context))
- {
- await _next(context);
- return;
- }
- var msisdn = context.Session.GetComplexData<string>("msisdn");
- if (!string.IsNullOrWhiteSpace(msisdn))
- {
- await _next(context);
- return;
- }
- context.Response.Headers.CacheControl = "no-store";
- if (IsAjaxRequest(context.Request))
- {
- context.Response.StatusCode = StatusCodes.Status401Unauthorized;
- context.Response.Headers["X-Login-Required"] = "true";
- await context.Response.WriteAsJsonAsync(new
- {
- success = false,
- errorCode = Common.CommonErrorCode.LoginRequired,
- redirectUrl = "mytel://back"
- });
- return;
- }
- context.Response.Redirect("mytel://back");
- }
- private static bool ShouldSkip(HttpContext context)
- {
- var path = context.Request.Path;
- if (path.StartsWithSegments("/Login")) return true;
- if (path.StartsWithSegments("/Home/ChangeLanguage")) return true;
- if (path.StartsWithSegments("/favicon.ico")) return true;
- if (path.StartsWithSegments("/kitty")) return true;
- if (path.StartsWithSegments("/css")) return true;
- if (path.StartsWithSegments("/js")) return true;
- if (path.StartsWithSegments("/lib")) return true;
- if (path.StartsWithSegments("/assets")) return true;
- return false;
- }
- private static bool IsAjaxRequest(HttpRequest request)
- {
- return string.Equals(request.Headers["X-Requested-With"], "XMLHttpRequest", StringComparison.OrdinalIgnoreCase)
- || string.Equals(request.Headers["Sec-Fetch-Dest"], "empty", StringComparison.OrdinalIgnoreCase)
- || request.Headers.Accept.Any(x => x?.Contains("application/json", StringComparison.OrdinalIgnoreCase) == true);
- }
- }
|