| | | 1 | | using Microsoft.AspNetCore.Http; |
| | | 2 | | using Microsoft.AspNetCore.Identity; |
| | | 3 | | using OzonRepositories.Context.Identity; |
| | | 4 | | |
| | | 5 | | namespace OzonOrdersWeb.Middleware |
| | | 6 | | { |
| | | 7 | | public class ImpersonationMiddleware |
| | | 8 | | { |
| | | 9 | | private readonly RequestDelegate _next; |
| | | 10 | | |
| | 0 | 11 | | public ImpersonationMiddleware(RequestDelegate next) |
| | | 12 | | { |
| | 0 | 13 | | _next = next; |
| | 0 | 14 | | } |
| | | 15 | | |
| | | 16 | | public async Task InvokeAsync(HttpContext context, |
| | | 17 | | UserManager<CustomIdentityUser> userManager, |
| | | 18 | | SignInManager<CustomIdentityUser> signInManager) |
| | | 19 | | { |
| | 0 | 20 | | var path = context.Request.Path; |
| | 0 | 21 | | if (path.StartsWithSegments("/Impersonation", out var remaining)) |
| | | 22 | | { |
| | | 23 | | // Mark the request so other middleware can recognise this as an impersonation entry |
| | 0 | 24 | | context.Items["IsImpersonationEntry"] = true; |
| | | 25 | | // Если есть cookie с Id пользователя для имперсонации, используем его для установки User |
| | 0 | 26 | | if (context.Request.Cookies.TryGetValue("ImpersonationUserId", out var userId) && !string.IsNullOrEmpty( |
| | | 27 | | { |
| | 0 | 28 | | var user = await userManager.FindByIdAsync(userId); |
| | 0 | 29 | | if (user != null) |
| | | 30 | | { |
| | 0 | 31 | | var principal = await signInManager.CreateUserPrincipalAsync(user); |
| | 0 | 32 | | if (principal != null) |
| | | 33 | | { |
| | 0 | 34 | | context.User = principal; |
| | | 35 | | } |
| | | 36 | | } |
| | | 37 | | } |
| | | 38 | | |
| | | 39 | | // Убираем префикс /Impersonation из пути и продолжаем обработку как обычно |
| | 0 | 40 | | context.Request.Path = remaining; |
| | | 41 | | } |
| | | 42 | | |
| | 0 | 43 | | await _next(context); |
| | 0 | 44 | | } |
| | | 45 | | } |
| | | 46 | | } |