| | | 1 | | using Microsoft.AspNetCore.Authorization; |
| | | 2 | | using Microsoft.AspNetCore.Identity; |
| | | 3 | | using Microsoft.AspNetCore.Mvc; |
| | | 4 | | using Microsoft.EntityFrameworkCore; |
| | | 5 | | using Newtonsoft.Json; |
| | | 6 | | using OzonDomains.ViewModels; |
| | | 7 | | using OzonOrdersWeb.ViewModels.UserViewModels; |
| | | 8 | | using OzonRepositories.Context; |
| | | 9 | | using OzonRepositories.Context.Identity; |
| | | 10 | | using OzonDomains.Models.AccessControl; |
| | | 11 | | using Services.FiltersServices.DataFilterManagers; |
| | | 12 | | using Services.FiltersServices.FilterModels; |
| | | 13 | | |
| | | 14 | | namespace OzonOrdersWeb.Controllers |
| | | 15 | | { |
| | | 16 | | [Authorize(Roles = "Admin")] |
| | | 17 | | [Area("Studio2")] |
| | | 18 | | public class UserController : Controller |
| | | 19 | | { |
| | | 20 | | private readonly UserManager<CustomIdentityUser> _userManager; |
| | | 21 | | private readonly RoleManager<IdentityRole> _roleManager; |
| | | 22 | | private readonly SignInManager<CustomIdentityUser> _signInManager; |
| | | 23 | | private readonly ApplicationDbContext _context; |
| | | 24 | | private readonly UserFilterManager _filter; |
| | 1 | 25 | | public UserController(UserManager<CustomIdentityUser> userManager, |
| | 1 | 26 | | RoleManager<IdentityRole> roleManager, |
| | 1 | 27 | | SignInManager<CustomIdentityUser> signInManager, |
| | 1 | 28 | | ApplicationDbContext context, |
| | 1 | 29 | | UserFilterManager userFilterManager) |
| | | 30 | | { |
| | 1 | 31 | | _userManager = userManager; |
| | 1 | 32 | | _roleManager = roleManager; |
| | 1 | 33 | | _signInManager = signInManager; |
| | 1 | 34 | | _context = context; |
| | 1 | 35 | | _filter = userFilterManager; |
| | 1 | 36 | | } |
| | | 37 | | /// <summary> |
| | | 38 | | /// Имперсонация пользователя (быстрое переключение). |
| | | 39 | | /// Только для админов. Открывать в новом окне! |
| | | 40 | | /// </summary> |
| | | 41 | | [HttpGet] |
| | | 42 | | [Authorize(Roles = "Admin")] |
| | | 43 | | public async Task<IActionResult> Impersonate(string userId) |
| | | 44 | | { |
| | 0 | 45 | | if (string.IsNullOrEmpty(userId)) |
| | 0 | 46 | | return BadRequest("UserId is required"); |
| | | 47 | | |
| | 0 | 48 | | var user = await _userManager.FindByIdAsync(userId); |
| | 0 | 49 | | if (user == null) |
| | 0 | 50 | | return NotFound("User not found"); |
| | | 51 | | |
| | | 52 | | // Устанавливаем cookie для имперсонации с ограниченным Path "/Impersonation" |
| | 0 | 53 | | var cookieOptions = new CookieOptions |
| | 0 | 54 | | { |
| | 0 | 55 | | HttpOnly = true, |
| | 0 | 56 | | Secure = true, |
| | 0 | 57 | | SameSite = SameSiteMode.Lax, |
| | 0 | 58 | | Path = "/Impersonation", |
| | 0 | 59 | | Expires = DateTimeOffset.UtcNow.AddMinutes(30) |
| | 0 | 60 | | }; |
| | | 61 | | |
| | 0 | 62 | | Response.Cookies.Append("ImpersonationUserId", user.Id, cookieOptions); |
| | | 63 | | |
| | | 64 | | // Перенаправляем в область /Impersonation — middleware применит имперсонированного пользователя |
| | 0 | 65 | | return Redirect("/Impersonation"); |
| | 0 | 66 | | } |
| | | 67 | | // Старый маршрут /User остаётся совместимым, но отдельного Index.cshtml больше нет. |
| | 1 | 68 | | public IActionResult Index() => RedirectToAction(nameof(UserList)); |
| | | 69 | | |
| | 0 | 70 | | public IActionResult CreateRole() => View(); |
| | | 71 | | [HttpPost] |
| | | 72 | | public async Task<IActionResult> CreateRole(string name) |
| | | 73 | | { |
| | 0 | 74 | | if (!string.IsNullOrEmpty(name)) |
| | | 75 | | { |
| | 0 | 76 | | IdentityResult result = await _roleManager.CreateAsync(new IdentityRole(name)); |
| | 0 | 77 | | if (result.Succeeded) |
| | | 78 | | { |
| | 0 | 79 | | return RedirectToAction("Index"); |
| | | 80 | | } |
| | | 81 | | else |
| | | 82 | | { |
| | 0 | 83 | | foreach (var error in result.Errors) |
| | | 84 | | { |
| | 0 | 85 | | ModelState.AddModelError(string.Empty, error.Description); |
| | | 86 | | } |
| | | 87 | | } |
| | | 88 | | } |
| | 0 | 89 | | return View(name); |
| | 0 | 90 | | } |
| | | 91 | | |
| | | 92 | | [HttpPost] |
| | | 93 | | public async Task<IActionResult> Delete(string id) |
| | | 94 | | { |
| | 0 | 95 | | IdentityRole? role = await _roleManager.FindByIdAsync(id); |
| | 0 | 96 | | if (role != null) |
| | | 97 | | { |
| | 0 | 98 | | IdentityResult result = await _roleManager.DeleteAsync(role); |
| | | 99 | | } |
| | 0 | 100 | | return RedirectToAction("Index"); |
| | 0 | 101 | | } |
| | | 102 | | |
| | | 103 | | public async Task<IActionResult> UserList(int page = 1) |
| | | 104 | | { |
| | | 105 | | |
| | 0 | 106 | | var usersWithUserAccess = _userManager.Users.Include(u => u.AccessProfile).ToList(); |
| | 0 | 107 | | var accesses = _context.AccessProfiles.ToList(); |
| | 0 | 108 | | var roles = _roleManager.Roles.Select(r => r.Name).ToList(); |
| | 0 | 109 | | var accessDictionary = accesses.ToDictionary(a => a.Id); |
| | | 110 | | |
| | 0 | 111 | | foreach (var user in usersWithUserAccess) |
| | | 112 | | { |
| | 0 | 113 | | if (user.AccessProfileId.HasValue && accessDictionary.ContainsKey(user.AccessProfileId.Value)) |
| | | 114 | | { |
| | 0 | 115 | | user.AccessProfile = accessDictionary[user.AccessProfileId.Value]; |
| | | 116 | | } |
| | | 117 | | } |
| | | 118 | | |
| | 0 | 119 | | ViewBag.Accesses = accesses; |
| | | 120 | | |
| | 0 | 121 | | var filterDataString = HttpContext.Request.Cookies["UserFilterData"]; |
| | 0 | 122 | | var filterData = new UserFilterModel(); |
| | 0 | 123 | | if (!string.IsNullOrEmpty(filterDataString)) |
| | | 124 | | { |
| | 0 | 125 | | filterData = JsonConvert.DeserializeObject<UserFilterModel>(filterDataString) ?? filterData; |
| | 0 | 126 | | usersWithUserAccess = await _filter.FilterByFilterData(usersWithUserAccess, filterData); |
| | | 127 | | } |
| | 0 | 128 | | ViewBag.Roles = roles; // Передаем список ролей в ViewBag |
| | | 129 | | |
| | 0 | 130 | | return View(new PageViewModel<CustomIdentityUser, UserFilterModel>(usersWithUserAccess, page, 15, filterData |
| | 0 | 131 | | } |
| | | 132 | | |
| | | 133 | | [HttpPost] |
| | | 134 | | public async Task<IActionResult> UserList(UserFilterModel filterModel, int page = 1) |
| | | 135 | | { |
| | 0 | 136 | | var serializedFilterData = JsonConvert.SerializeObject(filterModel); |
| | 0 | 137 | | HttpContext.Response.Cookies.Append("UserFilterData", serializedFilterData); |
| | 0 | 138 | | var roles = _roleManager.Roles.Select(r => r.Name).ToList(); |
| | 0 | 139 | | var usersWithUserAccess = _userManager.Users.Include(u => u.AccessProfile).ToList(); |
| | 0 | 140 | | var accesses = _context.AccessProfiles.ToList(); |
| | | 141 | | |
| | 0 | 142 | | var accessDictionary = accesses.ToDictionary(a => a.Id); |
| | | 143 | | |
| | 0 | 144 | | foreach (var user in usersWithUserAccess) |
| | | 145 | | { |
| | 0 | 146 | | if (user.AccessProfileId.HasValue && accessDictionary.ContainsKey(user.AccessProfileId.Value)) |
| | | 147 | | { |
| | 0 | 148 | | user.AccessProfile = accessDictionary[user.AccessProfileId.Value]; |
| | | 149 | | } |
| | | 150 | | } |
| | | 151 | | |
| | 0 | 152 | | ViewBag.Accesses = accesses; |
| | 0 | 153 | | ViewBag.Roles = roles; // Передаем список ролей в ViewBag |
| | | 154 | | // Фильтруем пользователей по модели фильтрации |
| | 0 | 155 | | var filteredUsers = await _filter.FilterByFilterData(usersWithUserAccess, filterModel); |
| | | 156 | | |
| | | 157 | | // Возвращаем обновленное представление |
| | 0 | 158 | | return View(new PageViewModel<CustomIdentityUser, UserFilterModel>(filteredUsers, page, 15, filterModel)); |
| | 0 | 159 | | } |
| | | 160 | | |
| | | 161 | | |
| | | 162 | | |
| | | 163 | | public async Task<IActionResult> Edit(string userId) |
| | | 164 | | { |
| | | 165 | | // получаем пользователя |
| | 0 | 166 | | CustomIdentityUser? user = await _userManager.FindByIdAsync(userId); |
| | 0 | 167 | | if (user != null) |
| | | 168 | | { |
| | | 169 | | // получем список ролей пользователя |
| | 0 | 170 | | var userRoles = await _userManager.GetRolesAsync(user); |
| | 0 | 171 | | var allRoles = _roleManager.Roles.ToList(); |
| | 0 | 172 | | ChangeRoleViewModel model = new ChangeRoleViewModel |
| | 0 | 173 | | { |
| | 0 | 174 | | UserId = user.Id, |
| | 0 | 175 | | UserEmail = user.Email ?? string.Empty, |
| | 0 | 176 | | UserRoles = userRoles, |
| | 0 | 177 | | AllRoles = allRoles |
| | 0 | 178 | | }; |
| | 0 | 179 | | return View(model); |
| | | 180 | | } |
| | | 181 | | |
| | 0 | 182 | | return NotFound(); |
| | 0 | 183 | | } |
| | | 184 | | |
| | | 185 | | [HttpPost] |
| | | 186 | | [ValidateAntiForgeryToken] |
| | | 187 | | public async Task<IActionResult> Edit(string id, List<string> roles) |
| | | 188 | | { |
| | 0 | 189 | | var existingUser = await _userManager.FindByIdAsync(id); |
| | 0 | 190 | | if (existingUser == null) return NotFound(); |
| | | 191 | | |
| | 0 | 192 | | var currentRoles = await _userManager.GetRolesAsync(existingUser); |
| | 0 | 193 | | await _userManager.RemoveFromRolesAsync(existingUser, currentRoles); |
| | 0 | 194 | | if (roles?.Any() == true) |
| | 0 | 195 | | await _userManager.AddToRolesAsync(existingUser, roles); |
| | | 196 | | |
| | 0 | 197 | | TempData["SuccessMessage"] = $"Роли пользователя {existingUser.UserName} обновлены."; |
| | 0 | 198 | | return RedirectToAction(nameof(UserList)); |
| | 0 | 199 | | } |
| | | 200 | | |
| | | 201 | | |
| | | 202 | | [HttpPost] |
| | | 203 | | [ValidateAntiForgeryToken] |
| | | 204 | | public async Task<IActionResult> EditUserAccess(string id, CustomIdentityUser user) |
| | | 205 | | { |
| | 0 | 206 | | if (id != user.Id) |
| | | 207 | | { |
| | 0 | 208 | | return NotFound(); |
| | | 209 | | } |
| | | 210 | | |
| | 0 | 211 | | if (ModelState.IsValid) |
| | | 212 | | { |
| | 0 | 213 | | var existingUser = await _userManager.FindByIdAsync(id); |
| | 0 | 214 | | if (existingUser != null) |
| | | 215 | | { |
| | 0 | 216 | | existingUser.AccessProfileId = user.AccessProfileId; |
| | | 217 | | |
| | 0 | 218 | | var result = await _userManager.UpdateAsync(existingUser); |
| | 0 | 219 | | if (result.Succeeded) |
| | | 220 | | { |
| | 0 | 221 | | return RedirectToAction(nameof(UserList)); |
| | | 222 | | } |
| | | 223 | | else |
| | | 224 | | { |
| | 0 | 225 | | foreach (var error in result.Errors) |
| | | 226 | | { |
| | 0 | 227 | | ModelState.AddModelError(string.Empty, error.Description); |
| | | 228 | | } |
| | | 229 | | } |
| | | 230 | | } |
| | | 231 | | else |
| | | 232 | | { |
| | 0 | 233 | | return NotFound(); |
| | | 234 | | } |
| | | 235 | | } |
| | | 236 | | |
| | 0 | 237 | | return View(user); |
| | 0 | 238 | | } |
| | | 239 | | |
| | | 240 | | [HttpGet] |
| | | 241 | | public IActionResult Create() |
| | | 242 | | { |
| | 0 | 243 | | return View(); |
| | | 244 | | } |
| | | 245 | | |
| | | 246 | | [HttpPost] |
| | | 247 | | public async Task<IActionResult> Create(RegisterViewModel model) |
| | | 248 | | { |
| | 0 | 249 | | if (ModelState.IsValid) |
| | | 250 | | { |
| | 0 | 251 | | var user = new CustomIdentityUser { UserName = model.Username, Email = model.Username }; |
| | | 252 | | |
| | 0 | 253 | | var result = await _userManager.CreateAsync(user, model.Password); |
| | | 254 | | |
| | 0 | 255 | | if (result.Succeeded) |
| | | 256 | | { |
| | 0 | 257 | | var roleExists = await _roleManager.RoleExistsAsync("user"); |
| | 0 | 258 | | if (!roleExists) |
| | | 259 | | { |
| | 0 | 260 | | await _roleManager.CreateAsync(new IdentityRole("user")); |
| | | 261 | | } |
| | 0 | 262 | | await _userManager.AddToRoleAsync(user, "user"); |
| | | 263 | | |
| | 0 | 264 | | return RedirectToAction("Index", "Home"); |
| | | 265 | | } |
| | | 266 | | |
| | 0 | 267 | | foreach (var error in result.Errors) |
| | | 268 | | { |
| | 0 | 269 | | ModelState.AddModelError(string.Empty, error.Description); |
| | | 270 | | } |
| | 0 | 271 | | } |
| | | 272 | | |
| | 0 | 273 | | return View(model); |
| | 0 | 274 | | } |
| | | 275 | | |
| | | 276 | | public async Task<IActionResult> SetAccessProfile(string userId) |
| | | 277 | | { |
| | 0 | 278 | | await Task.CompletedTask; |
| | 0 | 279 | | var viewModel = new SetUserAccessViewModel |
| | 0 | 280 | | { |
| | 0 | 281 | | AccessProfiles = _context.AccessProfiles.ToList(), |
| | 0 | 282 | | UserId = userId |
| | 0 | 283 | | }; |
| | | 284 | | |
| | 0 | 285 | | return View(viewModel); |
| | 0 | 286 | | } |
| | | 287 | | |
| | | 288 | | [HttpPost] |
| | | 289 | | public async Task<IActionResult> SetAccessProfile(SetUserAccessViewModel viewModel) |
| | | 290 | | { |
| | 0 | 291 | | if (viewModel.UserId != null && viewModel.SelectedAccessProfileId != null) |
| | | 292 | | { |
| | 0 | 293 | | var user = await _userManager.FindByIdAsync(viewModel.UserId); |
| | 0 | 294 | | var access = await _context.AccessProfiles.FindAsync(viewModel.SelectedAccessProfileId); |
| | 0 | 295 | | if (user != null) |
| | | 296 | | { |
| | 0 | 297 | | user.AccessProfile = access; |
| | 0 | 298 | | await _userManager.UpdateAsync(user); |
| | 0 | 299 | | return RedirectToAction("UserList"); |
| | | 300 | | } |
| | 0 | 301 | | } |
| | | 302 | | |
| | 0 | 303 | | viewModel.AccessProfiles = await _context.AccessProfiles.ToListAsync(); |
| | | 304 | | |
| | 0 | 305 | | return View(viewModel); |
| | 0 | 306 | | } |
| | | 307 | | |
| | | 308 | | /// <summary> |
| | | 309 | | /// Разблокирует аккаунт пользователя |
| | | 310 | | /// </summary> |
| | | 311 | | [HttpPost] |
| | | 312 | | [ValidateAntiForgeryToken] |
| | | 313 | | public async Task<IActionResult> UnlockUser(string userId) |
| | | 314 | | { |
| | 0 | 315 | | if (string.IsNullOrEmpty(userId)) |
| | | 316 | | { |
| | 0 | 317 | | return BadRequest("ID пользователя не указан"); |
| | | 318 | | } |
| | | 319 | | |
| | 0 | 320 | | var user = await _userManager.FindByIdAsync(userId); |
| | 0 | 321 | | if (user == null) |
| | | 322 | | { |
| | 0 | 323 | | return NotFound("Пользователь не найден"); |
| | | 324 | | } |
| | | 325 | | |
| | | 326 | | // Снимаем блокировку аккаунта |
| | 0 | 327 | | var lockoutResult = await _userManager.SetLockoutEndDateAsync(user, null); |
| | | 328 | | // Сбрасываем счетчик неудачных попыток входа |
| | 0 | 329 | | var resetResult = await _userManager.ResetAccessFailedCountAsync(user); |
| | | 330 | | |
| | 0 | 331 | | if (lockoutResult.Succeeded && resetResult.Succeeded) |
| | | 332 | | { |
| | 0 | 333 | | TempData["SuccessMessage"] = $"Аккаунт пользователя {user.UserName} успешно разблокирован."; |
| | 0 | 334 | | return RedirectToAction(nameof(UserList)); |
| | | 335 | | } |
| | | 336 | | else |
| | | 337 | | { |
| | 0 | 338 | | var errors = lockoutResult.Errors.Concat(resetResult.Errors); |
| | 0 | 339 | | foreach (var error in errors) |
| | | 340 | | { |
| | 0 | 341 | | ModelState.AddModelError(string.Empty, error.Description); |
| | | 342 | | } |
| | 0 | 343 | | TempData["ErrorMessage"] = "Ошибка при разблокировке аккаунта."; |
| | 0 | 344 | | return RedirectToAction(nameof(UserList)); |
| | | 345 | | } |
| | 0 | 346 | | } |
| | | 347 | | |
| | | 348 | | /// <summary> |
| | | 349 | | /// Блокирует аккаунт пользователя |
| | | 350 | | /// </summary> |
| | | 351 | | [HttpPost] |
| | | 352 | | [ValidateAntiForgeryToken] |
| | | 353 | | public async Task<IActionResult> LockUser(string userId, string lockoutType, DateTime? lockoutDate) |
| | | 354 | | { |
| | 0 | 355 | | if (string.IsNullOrEmpty(userId)) |
| | | 356 | | { |
| | 0 | 357 | | return BadRequest("ID пользователя не указан"); |
| | | 358 | | } |
| | | 359 | | |
| | 0 | 360 | | var user = await _userManager.FindByIdAsync(userId); |
| | 0 | 361 | | if (user == null) |
| | | 362 | | { |
| | 0 | 363 | | return NotFound("Пользователь не найден"); |
| | | 364 | | } |
| | | 365 | | |
| | | 366 | | // Проверяем, не является ли пользователь администратором |
| | 0 | 367 | | var roles = await _userManager.GetRolesAsync(user); |
| | 0 | 368 | | if (roles.Contains("Admin")) |
| | | 369 | | { |
| | 0 | 370 | | TempData["ErrorMessage"] = "Нельзя заблокировать аккаунт администратора."; |
| | 0 | 371 | | return RedirectToAction(nameof(UserList)); |
| | | 372 | | } |
| | | 373 | | |
| | 0 | 374 | | DateTimeOffset? lockoutEndDate = null; |
| | | 375 | | |
| | 0 | 376 | | if (lockoutType == "permanent") |
| | | 377 | | { |
| | | 378 | | // Блокировка навсегда (используем максимальную дату) |
| | 0 | 379 | | lockoutEndDate = DateTimeOffset.MaxValue; |
| | | 380 | | } |
| | 0 | 381 | | else if (lockoutType == "temporary" && lockoutDate.HasValue) |
| | | 382 | | { |
| | | 383 | | // Временная блокировка до указанной даты |
| | | 384 | | // Используем локальное время пользователя |
| | 0 | 385 | | lockoutEndDate = new DateTimeOffset(lockoutDate.Value, TimeZoneInfo.Local.GetUtcOffset(lockoutDate.Value |
| | | 386 | | } |
| | | 387 | | else |
| | | 388 | | { |
| | 0 | 389 | | TempData["ErrorMessage"] = "Неверные параметры блокировки."; |
| | 0 | 390 | | return RedirectToAction(nameof(UserList)); |
| | | 391 | | } |
| | | 392 | | |
| | | 393 | | // Устанавливаем дату окончания блокировки |
| | 0 | 394 | | var lockoutResult = await _userManager.SetLockoutEndDateAsync(user, lockoutEndDate); |
| | | 395 | | // Увеличиваем счетчик неудачных попыток, чтобы активировать блокировку |
| | 0 | 396 | | await _userManager.AccessFailedAsync(user); |
| | | 397 | | |
| | | 398 | | // Инвалидируем все сессии пользователя (выбрасывает из системы) |
| | 0 | 399 | | await _userManager.UpdateSecurityStampAsync(user); |
| | | 400 | | |
| | 0 | 401 | | if (lockoutResult.Succeeded) |
| | | 402 | | { |
| | | 403 | | // Если пользователь сейчас залогинен, разлогиниваем его |
| | 0 | 404 | | var currentUser = await _userManager.GetUserAsync(User); |
| | 0 | 405 | | if (currentUser != null && currentUser.Id == user.Id) |
| | | 406 | | { |
| | | 407 | | // Если блокируется текущий пользователь (что маловероятно, но на всякий случай) |
| | 0 | 408 | | await _signInManager.SignOutAsync(); |
| | | 409 | | } |
| | | 410 | | |
| | | 411 | | // Проверяем, залогинен ли заблокированный пользователь в другом месте |
| | | 412 | | // Инвалидация SecurityStamp автоматически разлогинит пользователя при следующем запросе |
| | | 413 | | |
| | 0 | 414 | | string message = lockoutType == "permanent" |
| | 0 | 415 | | ? $"Аккаунт пользователя {user.UserName} заблокирован навсегда. Пользователь будет разлогинен из все |
| | 0 | 416 | | : $"Аккаунт пользователя {user.UserName} заблокирован до {lockoutEndDate!.Value.LocalDateTime:dd.MM. |
| | 0 | 417 | | TempData["SuccessMessage"] = message; |
| | 0 | 418 | | return RedirectToAction(nameof(UserList)); |
| | | 419 | | } |
| | | 420 | | else |
| | | 421 | | { |
| | 0 | 422 | | foreach (var error in lockoutResult.Errors) |
| | | 423 | | { |
| | 0 | 424 | | ModelState.AddModelError(string.Empty, error.Description); |
| | | 425 | | } |
| | 0 | 426 | | TempData["ErrorMessage"] = "Ошибка при блокировке аккаунта."; |
| | 0 | 427 | | return RedirectToAction(nameof(UserList)); |
| | | 428 | | } |
| | 0 | 429 | | } |
| | | 430 | | |
| | | 431 | | } |
| | | 432 | | } |