| | | 1 | | // Licensed to the .NET Foundation under one or more agreements. |
| | | 2 | | // The .NET Foundation licenses this file to you under the MIT license. |
| | | 3 | | #nullable disable |
| | | 4 | | |
| | | 5 | | using System; |
| | | 6 | | using System.Collections.Generic; |
| | | 7 | | using System.ComponentModel.DataAnnotations; |
| | | 8 | | using System.Linq; |
| | | 9 | | using System.Threading.Tasks; |
| | | 10 | | using Microsoft.AspNetCore.Authorization; |
| | | 11 | | using Microsoft.AspNetCore.Authentication; |
| | | 12 | | using Microsoft.AspNetCore.Http; |
| | | 13 | | using Microsoft.AspNetCore.Identity; |
| | | 14 | | using Microsoft.AspNetCore.Identity.UI.Services; |
| | | 15 | | using Microsoft.AspNetCore.Mvc; |
| | | 16 | | using Microsoft.AspNetCore.Mvc.RazorPages; |
| | | 17 | | using Microsoft.AspNetCore.RateLimiting; |
| | | 18 | | using Microsoft.Extensions.Logging; |
| | | 19 | | using OzonOrdersWeb.Extensions; |
| | | 20 | | using OzonRepositories.Context.Identity; |
| | | 21 | | using SlqStudio.Application.Services.EmailService; |
| | | 22 | | |
| | | 23 | | namespace OzonOrdersWeb.Areas.Identity.Pages.Account |
| | | 24 | | { |
| | | 25 | | [EnableRateLimiting("auth")] |
| | | 26 | | public class LoginModel : PageModel |
| | | 27 | | { |
| | | 28 | | private readonly SignInManager<CustomIdentityUser> _signInManager; |
| | | 29 | | private readonly UserManager<CustomIdentityUser> _userManager; |
| | | 30 | | private readonly ILogger<LoginModel> _logger; |
| | | 31 | | private readonly IEmailService _emailService; |
| | | 32 | | |
| | 0 | 33 | | public LoginModel( |
| | 0 | 34 | | SignInManager<CustomIdentityUser> signInManager, |
| | 0 | 35 | | UserManager<CustomIdentityUser> userManager, |
| | 0 | 36 | | ILogger<LoginModel> logger, |
| | 0 | 37 | | IEmailService emailService = null) |
| | | 38 | | { |
| | 0 | 39 | | _signInManager = signInManager; |
| | 0 | 40 | | _userManager = userManager; |
| | 0 | 41 | | _logger = logger; |
| | 0 | 42 | | _emailService = emailService; |
| | 0 | 43 | | } |
| | | 44 | | |
| | | 45 | | /// <summary> |
| | | 46 | | /// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used |
| | | 47 | | /// directly from your code. This API may change or be removed in future releases. |
| | | 48 | | /// </summary> |
| | | 49 | | [BindProperty] |
| | 0 | 50 | | public InputModel Input { get; set; } |
| | | 51 | | |
| | | 52 | | /// <summary> |
| | | 53 | | /// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used |
| | | 54 | | /// directly from your code. This API may change or be removed in future releases. |
| | | 55 | | /// </summary> |
| | 0 | 56 | | public IList<AuthenticationScheme> ExternalLogins { get; set; } |
| | | 57 | | |
| | | 58 | | /// <summary> |
| | | 59 | | /// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used |
| | | 60 | | /// directly from your code. This API may change or be removed in future releases. |
| | | 61 | | /// </summary> |
| | 0 | 62 | | public string ReturnUrl { get; set; } |
| | | 63 | | |
| | | 64 | | /// <summary> |
| | | 65 | | /// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used |
| | | 66 | | /// directly from your code. This API may change or be removed in future releases. |
| | | 67 | | /// </summary> |
| | | 68 | | [TempData] |
| | 0 | 69 | | public string ErrorMessage { get; set; } |
| | | 70 | | |
| | | 71 | | /// <summary> |
| | | 72 | | /// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used |
| | | 73 | | /// directly from your code. This API may change or be removed in future releases. |
| | | 74 | | /// </summary> |
| | | 75 | | public class InputModel |
| | | 76 | | { |
| | | 77 | | /// <summary> |
| | | 78 | | /// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used |
| | | 79 | | /// directly from your code. This API may change or be removed in future releases. |
| | | 80 | | /// </summary> |
| | | 81 | | [Required(ErrorMessage = "Логин или email обязателен для заполнения")] |
| | | 82 | | [Display(Name = "Логин или email")] |
| | 0 | 83 | | public string Username { get; set; } |
| | | 84 | | |
| | | 85 | | /// <summary> |
| | | 86 | | /// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used |
| | | 87 | | /// directly from your code. This API may change or be removed in future releases. |
| | | 88 | | /// </summary> |
| | | 89 | | [Required(ErrorMessage = "Пароль обязателен для заполнения")] |
| | | 90 | | [DataType(DataType.Password)] |
| | | 91 | | [Display(Name = "Пароль")] |
| | 0 | 92 | | public string Password { get; set; } |
| | | 93 | | |
| | | 94 | | /// <summary> |
| | | 95 | | /// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used |
| | | 96 | | /// directly from your code. This API may change or be removed in future releases. |
| | | 97 | | /// </summary> |
| | | 98 | | [Display(Name = "Запомнить меня")] |
| | 0 | 99 | | public bool RememberMe { get; set; } |
| | | 100 | | } |
| | | 101 | | |
| | | 102 | | public async Task OnGetAsync(string returnUrl = null) |
| | | 103 | | { |
| | 0 | 104 | | if (!string.IsNullOrEmpty(ErrorMessage)) |
| | | 105 | | { |
| | 0 | 106 | | ModelState.AddModelError(string.Empty, ErrorMessage); |
| | | 107 | | } |
| | | 108 | | |
| | | 109 | | // Проверяем наличие сообщения об ошибке в query string (от Rate Limiting) |
| | 0 | 110 | | var errorParam = Request.Query["error"].ToString(); |
| | 0 | 111 | | if (!string.IsNullOrEmpty(errorParam)) |
| | | 112 | | { |
| | 0 | 113 | | ModelState.AddModelError(string.Empty, errorParam); |
| | | 114 | | } |
| | | 115 | | |
| | | 116 | | // Проверяем, был ли пользователь разлогинен из-за блокировки |
| | 0 | 117 | | var lockedParam = Request.Query["locked"].ToString(); |
| | 0 | 118 | | if (!string.IsNullOrEmpty(lockedParam) && lockedParam == "true") |
| | | 119 | | { |
| | 0 | 120 | | ModelState.AddModelError(string.Empty, "Ваш аккаунт был заблокирован. Обратитесь к администратору."); |
| | | 121 | | } |
| | | 122 | | |
| | 0 | 123 | | returnUrl ??= "/Studio2/OrdersGrid"; |
| | | 124 | | |
| | | 125 | | // Clear the existing external cookie to ensure a clean login process |
| | 0 | 126 | | await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme); |
| | | 127 | | |
| | 0 | 128 | | ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList(); |
| | | 129 | | |
| | 0 | 130 | | ReturnUrl = returnUrl; |
| | 0 | 131 | | } |
| | | 132 | | |
| | | 133 | | public async Task<IActionResult> OnPostAsync(string returnUrl = null) |
| | | 134 | | { |
| | 0 | 135 | | returnUrl = Url.IsLocalUrl(returnUrl) |
| | 0 | 136 | | ? LocalRedirectUrlEncoder.Encode(returnUrl) |
| | 0 | 137 | | : "/Studio2/OrdersGrid"; |
| | | 138 | | |
| | 0 | 139 | | ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList(); |
| | | 140 | | |
| | 0 | 141 | | if (ModelState.IsValid) |
| | | 142 | | { |
| | 0 | 143 | | var user = await FindUserByLoginOrEmailAsync(Input.Username); |
| | 0 | 144 | | if (user == null) |
| | | 145 | | { |
| | 0 | 146 | | LogAuthenticationWarning("LoginUserNotFound", Input.Username); |
| | 0 | 147 | | ModelState.AddModelError(string.Empty, "Пользователь с таким логином/email не найден."); |
| | 0 | 148 | | return Page(); |
| | | 149 | | } |
| | | 150 | | |
| | 0 | 151 | | if (!user.EmailConfirmed) |
| | | 152 | | { |
| | 0 | 153 | | LogAuthenticationWarning("LoginEmailNotConfirmed", Input.Username, user.Id); |
| | 0 | 154 | | ModelState.AddModelError(string.Empty, "Вход запрещен: email не подтвержден."); |
| | 0 | 155 | | return Page(); |
| | | 156 | | } |
| | | 157 | | |
| | 0 | 158 | | bool isAdmin = false; |
| | 0 | 159 | | var roles = await _userManager.GetRolesAsync(user); |
| | 0 | 160 | | isAdmin = roles.Contains("Admin"); |
| | | 161 | | |
| | | 162 | | // Если пользователь - администратор и аккаунт заблокирован, разблокируем его |
| | 0 | 163 | | if (isAdmin && await _userManager.IsLockedOutAsync(user)) |
| | | 164 | | { |
| | 0 | 165 | | await _userManager.SetLockoutEndDateAsync(user, null); |
| | 0 | 166 | | await _userManager.ResetAccessFailedCountAsync(user); |
| | 0 | 167 | | _logger.LogInformation("Аккаунт администратора {Username} автоматически разблокирован при попытке вх |
| | | 168 | | } |
| | | 169 | | |
| | 0 | 170 | | if (isAdmin) |
| | | 171 | | { |
| | 0 | 172 | | _logger.LogInformation("Попытка входа администратора {Username} - блокировка аккаунта отключена.", I |
| | | 173 | | } |
| | | 174 | | |
| | | 175 | | // Для администраторов отключаем блокировку аккаунта |
| | 0 | 176 | | bool lockoutOnFailure = !isAdmin; |
| | | 177 | | |
| | 0 | 178 | | var result = await _signInManager.CheckPasswordSignInAsync(user, Input.Password, lockoutOnFailure); |
| | 0 | 179 | | if (result.Succeeded) |
| | | 180 | | { |
| | 0 | 181 | | if (!user.IsAdminApproved) |
| | | 182 | | { |
| | 0 | 183 | | LogAuthenticationWarning("LoginNotApproved", Input.Username, user.Id); |
| | 0 | 184 | | ModelState.AddModelError(string.Empty, "Вход запрещен: доступ еще не одобрен администратором."); |
| | 0 | 185 | | return Page(); |
| | | 186 | | } |
| | | 187 | | |
| | 0 | 188 | | await _signInManager.SignInAsync(user, new AuthenticationProperties |
| | 0 | 189 | | { |
| | 0 | 190 | | IsPersistent = Input.RememberMe, |
| | 0 | 191 | | RedirectUri = returnUrl |
| | 0 | 192 | | }); |
| | 0 | 193 | | _logger.LogInformation("Пользователь {Username} успешно вошел в систему.", Input.Username); |
| | | 194 | | |
| | | 195 | | // Сохраняем время начала сессии в cookie |
| | 0 | 196 | | var sessionStartTime = DateTime.Now.ToString("O"); |
| | 0 | 197 | | Response.Cookies.Append("SessionStartTime", sessionStartTime, new CookieOptions |
| | 0 | 198 | | { |
| | 0 | 199 | | HttpOnly = true, |
| | 0 | 200 | | Secure = Request.IsHttps, |
| | 0 | 201 | | SameSite = SameSiteMode.Lax, |
| | 0 | 202 | | Expires = Input.RememberMe ? DateTimeOffset.Now.AddDays(30) : DateTimeOffset.Now.AddHours(24) |
| | 0 | 203 | | }); |
| | | 204 | | |
| | 0 | 205 | | return LocalRedirect(returnUrl); |
| | | 206 | | } |
| | 0 | 207 | | if (result.RequiresTwoFactor) |
| | | 208 | | { |
| | 0 | 209 | | return RedirectToPage("./LoginWith2fa", new { ReturnUrl = returnUrl, RememberMe = Input.RememberMe } |
| | | 210 | | } |
| | 0 | 211 | | if (result.IsLockedOut) |
| | | 212 | | { |
| | 0 | 213 | | _logger.LogWarning("Аккаунт пользователя {Username} заблокирован из-за превышения лимита попыток вхо |
| | | 214 | | |
| | | 215 | | // Отправляем уведомление на email о блокировке аккаунта |
| | 0 | 216 | | await SendAccountLockedNotificationAsync(Input.Username); |
| | | 217 | | |
| | 0 | 218 | | ModelState.AddModelError(string.Empty, "Аккаунт временно заблокирован из-за превышения лимита попыто |
| | 0 | 219 | | return Page(); |
| | | 220 | | } |
| | | 221 | | else |
| | | 222 | | { |
| | | 223 | | // Отправляем уведомление на email о неудачной попытке входа |
| | 0 | 224 | | LogAuthenticationWarning("LoginInvalidPassword", Input.Username, user.Id); |
| | 0 | 225 | | await SendFailedLoginNotificationAsync(Input.Username); |
| | | 226 | | |
| | 0 | 227 | | ModelState.AddModelError(string.Empty, "Неверный пароль."); |
| | 0 | 228 | | return Page(); |
| | | 229 | | } |
| | | 230 | | } |
| | | 231 | | |
| | | 232 | | // If we got this far, something failed, redisplay form |
| | 0 | 233 | | LogAuthenticationWarning("LoginFormValidationFailed", Input?.Username); |
| | 0 | 234 | | return Page(); |
| | 0 | 235 | | } |
| | | 236 | | |
| | | 237 | | private async Task<CustomIdentityUser> FindUserByLoginOrEmailAsync(string loginOrEmail) |
| | | 238 | | { |
| | 0 | 239 | | if (string.IsNullOrWhiteSpace(loginOrEmail)) |
| | | 240 | | { |
| | 0 | 241 | | return null; |
| | | 242 | | } |
| | | 243 | | |
| | 0 | 244 | | var trimmed = loginOrEmail.Trim(); |
| | 0 | 245 | | var byUserName = await _userManager.FindByNameAsync(trimmed); |
| | 0 | 246 | | if (byUserName != null) |
| | | 247 | | { |
| | 0 | 248 | | return byUserName; |
| | | 249 | | } |
| | | 250 | | |
| | 0 | 251 | | return await _userManager.FindByEmailAsync(trimmed); |
| | 0 | 252 | | } |
| | | 253 | | |
| | | 254 | | /// <summary> |
| | | 255 | | /// Отправляет уведомление на email о неудачной попытке входа |
| | | 256 | | /// </summary> |
| | | 257 | | private async Task SendFailedLoginNotificationAsync(string username) |
| | | 258 | | { |
| | 0 | 259 | | if (_emailService == null) |
| | | 260 | | { |
| | 0 | 261 | | return; // Email сервис не настроен |
| | | 262 | | } |
| | | 263 | | |
| | | 264 | | try |
| | | 265 | | { |
| | 0 | 266 | | var clientIp = HttpContext.Connection.RemoteIpAddress?.ToString() ?? "Неизвестен"; |
| | 0 | 267 | | var timestamp = DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss"); |
| | 0 | 268 | | var userAgent = HttpContext.Request.Headers["User-Agent"].ToString(); |
| | | 269 | | |
| | 0 | 270 | | var subject = "⚠️ Неудачная попытка входа в систему"; |
| | 0 | 271 | | var body = $@" |
| | 0 | 272 | | <h2>Обнаружена неудачная попытка входа</h2> |
| | 0 | 273 | | <p><strong>Время:</strong> {timestamp}</p> |
| | 0 | 274 | | <p><strong>Логин:</strong> {System.Net.WebUtility.HtmlEncode(username)}</p> |
| | 0 | 275 | | <p><strong>IP адрес:</strong> {System.Net.WebUtility.HtmlEncode(clientIp)}</p> |
| | 0 | 276 | | <p><strong>User-Agent:</strong> {System.Net.WebUtility.HtmlEncode(userAgent)}</p> |
| | 0 | 277 | | <hr> |
| | 0 | 278 | | <p style=""color: #666; font-size: 12px;"">Это автоматическое уведомление системы безопасности.</p> |
| | 0 | 279 | | "; |
| | | 280 | | |
| | 0 | 281 | | await _emailService.SendEmailAsync(subject, body); |
| | 0 | 282 | | _logger.LogInformation("Отправлено уведомление на email о неудачной попытке входа для пользователя {User |
| | 0 | 283 | | } |
| | 0 | 284 | | catch (Exception ex) |
| | | 285 | | { |
| | 0 | 286 | | _logger.LogError(ex, "Ошибка при отправке уведомления на email о неудачной попытке входа"); |
| | 0 | 287 | | } |
| | 0 | 288 | | } |
| | | 289 | | |
| | | 290 | | private void LogAuthenticationWarning(string eventKind, string username, string userId = null) |
| | | 291 | | { |
| | 0 | 292 | | using (_logger.BeginScope(new Dictionary<string, object> |
| | 0 | 293 | | { |
| | 0 | 294 | | ["EventKind"] = eventKind, |
| | 0 | 295 | | ["EventCategory"] = "auth", |
| | 0 | 296 | | ["RequestPath"] = HttpContext.Request.Path.Value, |
| | 0 | 297 | | ["TraceId"] = HttpContext.TraceIdentifier, |
| | 0 | 298 | | ["UserId"] = userId, |
| | 0 | 299 | | ["RemoteIp"] = HttpContext.Connection.RemoteIpAddress?.ToString() |
| | 0 | 300 | | })) |
| | | 301 | | { |
| | 0 | 302 | | _logger.LogWarning("Неуспешная попытка входа для {Username}: {EventKind}", username, eventKind); |
| | 0 | 303 | | } |
| | 0 | 304 | | } |
| | | 305 | | |
| | | 306 | | /// <summary> |
| | | 307 | | /// Отправляет уведомление на email о блокировке аккаунта |
| | | 308 | | /// </summary> |
| | | 309 | | private async Task SendAccountLockedNotificationAsync(string username) |
| | | 310 | | { |
| | 0 | 311 | | if (_emailService == null) |
| | | 312 | | { |
| | 0 | 313 | | return; // Email сервис не настроен |
| | | 314 | | } |
| | | 315 | | |
| | | 316 | | try |
| | | 317 | | { |
| | 0 | 318 | | var clientIp = HttpContext.Connection.RemoteIpAddress?.ToString() ?? "Неизвестен"; |
| | 0 | 319 | | var timestamp = DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss"); |
| | 0 | 320 | | var userAgent = HttpContext.Request.Headers["User-Agent"].ToString(); |
| | | 321 | | |
| | 0 | 322 | | var subject = "🔒 Аккаунт заблокирован из-за превышения лимита попыток входа"; |
| | 0 | 323 | | var body = $@" |
| | 0 | 324 | | <h2>Аккаунт заблокирован</h2> |
| | 0 | 325 | | <p><strong>Время блокировки:</strong> {timestamp}</p> |
| | 0 | 326 | | <p><strong>Логин:</strong> {System.Net.WebUtility.HtmlEncode(username)}</p> |
| | 0 | 327 | | <p><strong>IP адрес:</strong> {System.Net.WebUtility.HtmlEncode(clientIp)}</p> |
| | 0 | 328 | | <p><strong>User-Agent:</strong> {System.Net.WebUtility.HtmlEncode(userAgent)}</p> |
| | 0 | 329 | | <p><strong>Причина:</strong> Превышен лимит неудачных попыток входа (5 попыток за 15 минут)</p> |
| | 0 | 330 | | <p><strong>Длительность блокировки:</strong> 15 минут</p> |
| | 0 | 331 | | <hr> |
| | 0 | 332 | | <p style=""color: #dc3545; font-weight: bold;"">⚠️ ВНИМАНИЕ: Возможна попытка несанкционированного доступа!</p> |
| | 0 | 333 | | <p style=""color: #666; font-size: 12px;"">Это автоматическое уведомление системы безопасности.</p> |
| | 0 | 334 | | "; |
| | | 335 | | |
| | 0 | 336 | | await _emailService.SendEmailAsync(subject, body); |
| | 0 | 337 | | _logger.LogInformation("Отправлено уведомление на email о блокировке аккаунта для пользователя {Username |
| | 0 | 338 | | } |
| | 0 | 339 | | catch (Exception ex) |
| | | 340 | | { |
| | 0 | 341 | | _logger.LogError(ex, "Ошибка при отправке уведомления на email о блокировке аккаунта"); |
| | 0 | 342 | | } |
| | 0 | 343 | | } |
| | | 344 | | } |
| | | 345 | | } |