public async Task <IActionResult> BlockCustomer(int iDCus, string reasonBlockCus, DateTime?dateUnBlock, string id_acc) { var admin = await _userManager.GetUserAsync(User); if (reasonBlockCus != null && reasonBlockCus != "") { Block block = new Block(); block.ID_User = iDCus; block.Reason = reasonBlockCus; block.UnLockDate = dateUnBlock; block.BlockDate = DateTime.Now; block.ModifiedDate = DateTime.Now; try { block.ID_Admin = _context.Admin.Where(q => q.Account_ID == admin.Id).SingleOrDefault().ID_Admin; } catch { StatusMessage = "Error Không tìm thấy id admin thích hợp"; } _context.Block.Add(block); var user = await _userManager.FindByIdAsync(id_acc); AspNetUsers USer = _context.AspNetUsers.Where(p => p.Id == id_acc).SingleOrDefault(); if (user == null && USer == null) { return(NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.")); } user.IsBlock = 1; USer.IsBlock = 1; _context.AspNetUsers.Attach(USer); _context.Entry(USer).State = Microsoft.EntityFrameworkCore.EntityState.Modified; var updateResult = await _userManager.UpdateAsync(user); if (!updateResult.Succeeded) { var a = user; StatusMessage = "Error Khóa không thành công"; return(RedirectToAction("Index", "ManageCustomers")); //var userId = await _userManager.GetUserIdAsync(user); //throw new InvalidOperationException($"Unexpected error occurred setting fields for user with ID '{userId}'."); } _context.Block.Add(block); _context.SaveChanges(); StatusMessage = "Khóa thành công"; return(RedirectToAction("Index", "ManageCustomers")); } else { StatusMessage = "Error Khóa không có lí do"; } return(RedirectToAction("Index", "ManageCustomers")); }
public async Task <JsonResult> AddFavorite(int idpost) { var user = await _userManager.GetUserAsync(User); var post_Favoritecount = _context.Post_Favorite.Where(p => p.ID_Post == idpost && p.ID_User == user.Id).Count(); if (post_Favoritecount > 0) { return(Json(new { Result = "ERROR", Message = "Đã có trong danh sách yêu thích" })); } try { Post_Favorite post_Favorite = new Post_Favorite(); post_Favorite.ID_Post = idpost; post_Favorite.ID_User = user.Id; post_Favorite.MortifiedDate = DateTime.Now; _context.Post_Favorite.Add(post_Favorite); _context.SaveChanges(); return(Json(new { Result = "OK", Message = "Đã thêm vào danh sách yêu thích" })); } catch (Exception ex) { return(Json(new { Result = "ERROR", Message = ex.Message })); } }
public async Task <IActionResult> DeletePost(int idpost, string reasonDeletePost) { var post = await _context.Post.FindAsync(idpost); if (post == null) { return(NotFound()); } Post_Status poststatus = new Post_Status(); if (post != null) { poststatus.ID_Post = post.ID_Post; var user = await _userManager.GetUserAsync(User); poststatus.ID_Account = user.Id; poststatus.Reason = reasonDeletePost; poststatus.Status = 7; poststatus.ModifiedDate = DateTime.Now; _context.Post_Status.Add(poststatus); } try { await _context.SaveChangesAsync(); post.Status = poststatus.ID_PostStatus; _context.Post.Attach(post); _context.Entry(post).State = Microsoft.EntityFrameworkCore.EntityState.Modified; _context.SaveChanges(); StatusMessage = "Xóa bài đăng thành công"; } catch { StatusMessage = "Error Xóa bài đăng không thành công"; } return(RedirectToAction(nameof(Index))); }
public async Task <IActionResult> BlockPost(int idpost, string reasonBlockPost, bool isreport = false) { if (reasonBlockPost == null) { return(NotFound()); } var post = await _context.Post.FindAsync(idpost); Post_Status poststatus = new Post_Status(); if (post != null) { poststatus.ID_Post = post.ID_Post; var user = await _userManager.GetUserAsync(User); poststatus.ID_Account = user.Id; poststatus.Reason = reasonBlockPost; poststatus.Status = 3; poststatus.ModifiedDate = DateTime.Now; _context.Post_Status.Add(poststatus); } try { if (isreport) { if (!checkIsReadRepost(idpost)) { StatusMessage = "Error Khóa bài đăng không thành công"; return(RedirectToAction(nameof(DetailReportPost), new { id = idpost })); } } await _context.SaveChangesAsync(); post.Status = poststatus.ID_PostStatus; _context.Post.Attach(post); _context.Entry(post).State = Microsoft.EntityFrameworkCore.EntityState.Modified; _context.SaveChanges(); StatusMessage = "Khóa bài đăng thành công"; } catch { StatusMessage = "Error Khóa bài đăng không thành công"; } if (isreport) { return(RedirectToAction(nameof(ListReportPost))); } return(RedirectToAction(nameof(Index))); }
public async Task <IActionResult> OnGetCallbackAsync(string returnUrl = null, string remoteError = null) { bool isExist = false; returnUrl = returnUrl ?? Url.Content("~/"); if (remoteError != null) { ErrorMessage = $"Error from external provider: {remoteError}"; return(RedirectToPage("./Login", new { ReturnUrl = returnUrl })); } var info = await _signInManager.GetExternalLoginInfoAsync(); if (info == null) { ErrorMessage = "Error loading external login information."; return(RedirectToPage("./Login", new { ReturnUrl = returnUrl })); } var userID = _context.AspNetUserLogins.Where(p => p.ProviderKey == info.ProviderKey && p.LoginProvider == info.LoginProvider).SingleOrDefault().UserId; var user = _context.AspNetUsers.Where(p => p.Id == userID).SingleOrDefault(); BDS_ML.Models.ModelDB.Admin admin = new Models.ModelDB.Admin(); Customer cus = new Customer(); if (user != null) { isExist = true; if (user.IsBlock != 0) { if (user.IsAdmin == 0) { cus = _context.Customer.Where(c => c.Account_ID == user.Id).SingleOrDefault(); var block = _context.Block.Where(b => b.ID_User == cus.ID_User).OrderBy(p => p.ModifiedDate).LastOrDefault(); if (block.UnLockDate <= DateTime.Now) { try { block.ModifiedDate = DateTime.Now.Date; user.IsBlock = 0; _context.AspNetUsers.Attach(user); _context.Entry(user).State = Microsoft.EntityFrameworkCore.EntityState.Modified; _context.Block.Attach(block); _context.Entry(block).State = Microsoft.EntityFrameworkCore.EntityState.Modified; _context.SaveChanges(); } catch { } } else { ErrorMessage = "Tài khoản bị khóa!. Lí do: " + block.Reason + "."; return(RedirectToPage("./Login", new { ReturnUrl = returnUrl })); } } if (user.IsAdmin == 1) { admin = _context.Admin.Where(c => c.Account_ID == user.Id).SingleOrDefault(); var block = _context.Block.Where(b => b.ID_User == admin.ID_Admin).OrderBy(p => p.ModifiedDate).LastOrDefault(); if (block.UnLockDate <= DateTime.Now) { try { block.ModifiedDate = DateTime.Now.Date; user.IsBlock = 0; _context.AspNetUsers.Attach(user); _context.Entry(user).State = Microsoft.EntityFrameworkCore.EntityState.Modified; _context.Block.Attach(block); _context.Entry(block).State = Microsoft.EntityFrameworkCore.EntityState.Modified; _context.SaveChanges(); } catch { } } else { ErrorMessage = "Tài khoản bị khóa!. Lí do: " + block.Reason + "."; return(RedirectToPage("./Login", new { ReturnUrl = returnUrl })); } } } } // Sign in the user with this external login provider if the user already has a login. var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent : false, bypassTwoFactor : true); if (result.Succeeded) { string urlavatar = ""; if (user.IsAdmin == 1) { admin = _context.Admin.Where(c => c.Account_ID == user.Id).SingleOrDefault(); urlavatar += admin.Avatar_URL; } else { cus = _context.Customer.Where(c => c.Account_ID == user.Id).SingleOrDefault(); urlavatar += cus.Avatar_URL; } HttpContext.Session.SetString("AvatarImage", urlavatar); _logger.LogInformation("{Name} logged in with {LoginProvider} provider.", info.Principal.Identity.Name, info.LoginProvider); return(LocalRedirect(returnUrl)); } if (result.IsLockedOut) { return(RedirectToPage("./Lockout")); } else if (isExist) { return(RedirectToPage("./ExternalExistEmail")); } else { // If the user does not have an account, then ask the user to create an account. ReturnUrl = returnUrl; LoginProvider = info.LoginProvider; if (info.Principal.HasClaim(c => c.Type == ClaimTypes.Email)) { Input = new InputModel { Email = info.Principal.FindFirstValue(ClaimTypes.Email), FirstName = info.Principal.FindFirstValue(ClaimTypes.GivenName), LastName = info.Principal.FindFirstValue(ClaimTypes.Surname), Address = info.Principal.FindFirstValue(ClaimTypes.Country), PhoneNumber = info.Principal.FindFirstValue(ClaimTypes.MobilePhone) }; } return(Page()); } }
public async Task <IActionResult> OnPostAsync() { if (!ModelState.IsValid) { return(Page()); } var user = await _userManager.GetUserAsync(User); if (user == null) { return(NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.")); } Customer customer = _context.Customer.Where(c => c.Account_ID == user.Id).SingleOrDefault(); var email = await _userManager.GetEmailAsync(user); if (Input.Email != email) { customer.Email = Input.Email; var setEmailResult = await _userManager.SetEmailAsync(user, Input.Email); if (!setEmailResult.Succeeded) { var userId = await _userManager.GetUserIdAsync(user); throw new InvalidOperationException($"Unexpected error occurred setting email for user with ID '{userId}'."); } } var phoneNumber = await _userManager.GetPhoneNumberAsync(user); if (Input.PhoneNumber != phoneNumber) { customer.PhoneNumber = Input.PhoneNumber; var setPhoneResult = await _userManager.SetPhoneNumberAsync(user, Input.PhoneNumber); if (!setPhoneResult.Succeeded) { var userId = await _userManager.GetUserIdAsync(user); throw new InvalidOperationException($"Unexpected error occurred setting phone number for user with ID '{userId}'."); } } if (Input.FirstName != customer.FirstName) { customer.FirstName = Input.FirstName; } if (Input.LastName != customer.LastName) { customer.LastName = Input.LastName; } if (Input.Address != customer.Address) { customer.Address = Input.Address; } customer.ModifiedDate = DateTime.Now; var updateResult = await _userManager.UpdateAsync(user); if (!updateResult.Succeeded) { var userId = await _userManager.GetUserIdAsync(user); throw new InvalidOperationException($"Unexpected error occurred setting fields for user with ID '{userId}'."); } else { try { _context.Customer.Attach(customer); _context.Entry(customer).State = Microsoft.EntityFrameworkCore.EntityState.Modified; _context.SaveChanges(); } catch { StatusMessage = "Error Cập nhật thông tin không thành công!"; return(RedirectToPage()); } } await _signInManager.RefreshSignInAsync(user); StatusMessage = "Thông tin của bạn đã được cập nhật"; return(RedirectToPage()); }
public async Task <IActionResult> OnPostAsync(IFormFile image, string returnUrl = null) { returnUrl = returnUrl ?? Url.Content("~/"); if (ModelState.IsValid) { var user = new ApplicationUser { UserName = Input.Email, Email = Input.Email, PhoneNumber = Input.PhoneNumber }; var result = await _userManager.CreateAsync(user, Input.Password); if (result.Succeeded) { await _userManager.AddToRoleAsync(user, "User"); _logger.LogInformation("User created a new account with password."); Customer customer = new Customer(); if (image != null) { string fileName = Path.GetFileName(image.FileName); if (fileName.Length > 30) { fileName = fileName.Substring(0, 30); } string extensionFileName = Path.GetExtension(fileName); fileName = fileName.Substring(0, fileName.Length - extensionFileName.Length) + "-" + DateTime.Now.ToString().Replace(" ", "").Replace(":", "").Replace("/", "") + extensionFileName; var path = Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot\images\avatars", fileName); using (var stream = new FileStream(path, FileMode.Create)) { await image.CopyToAsync(stream); } customer.Avatar_URL = fileName; } else { customer.Avatar_URL = "avatar_common.png"; } customer.Account_ID = user.Id; customer.FirstName = Input.FirstName; customer.LastName = Input.LastName; customer.PhoneNumber = Input.PhoneNumber; customer.Email = Input.Email; customer.Address = Input.Address; customer.ModifiedDate = DateTime.Now; customer.CreatedDate = DateTime.Now; try { _context.Customer.Add(customer); _context.SaveChanges(); _logger.LogInformation("Created a new customer with account."); } catch (Exception e) { _logger.LogInformation("Error a new customer with account." + "Error: " + e); } var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); var callbackUrl = Url.Page( "/Account/ConfirmEmail", pageHandler: null, values: new { userId = user.Id, code = code }, protocol: Request.Scheme); SendMail.sendMail($"Vui lòng xác nhận tài khoản của bạn bằng cách <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>nhấn vào đây</a>.", Input.Email, "Xác nhận email của bạn"); await _signInManager.SignInAsync(user, isPersistent : false); //return LocalRedirect(returnUrl); return(RedirectToPage("./ConfirmationEmailRegister")); } foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } // If we got this far, something failed, redisplay form return(Page()); }
public async Task <IActionResult> OnPostAsync(string returnUrl = null) { returnUrl = returnUrl ?? Url.Content("~/"); var user = _context.AspNetUsers.Where(p => p.UserName == Input.Email).SingleOrDefault(); if (user == null) { ModelState.AddModelError(string.Empty, "Đăng nhập không thành công!."); return(Page()); } BDS_ML.Models.ModelDB.Admin admin = new Models.ModelDB.Admin(); Customer cus = new Customer(); if (user.IsBlock != 0) { if (user.IsAdmin == 0) { cus = _context.Customer.Where(c => c.Account_ID == user.Id).SingleOrDefault(); var block = _context.Block.Where(b => b.ID_User == cus.ID_User).OrderBy(p => p.ModifiedDate).LastOrDefault(); if (block.UnLockDate.GetValueOrDefault().Date <= DateTime.Now.Date) { try { block.ModifiedDate = DateTime.Now.Date; user.IsBlock = 0; _context.AspNetUsers.Attach(user); _context.Entry(user).State = Microsoft.EntityFrameworkCore.EntityState.Modified; _context.Block.Attach(block); _context.Entry(block).State = Microsoft.EntityFrameworkCore.EntityState.Modified; _context.SaveChanges(); } catch { } } else { ModelState.AddModelError(string.Empty, "Tài khoản bị khóa!. Lí do: " + block.Reason); return(Page()); } } if (user.IsAdmin == 1) { admin = _context.Admin.Where(c => c.Account_ID == user.Id).SingleOrDefault(); var block = _context.Block.Where(b => b.ID_User == admin.ID_Admin).OrderBy(p => p.ModifiedDate).LastOrDefault(); if (block.UnLockDate <= DateTime.Now) { try { block.ModifiedDate = DateTime.Now.Date; user.IsBlock = 0; _context.AspNetUsers.Attach(user); _context.Entry(user).State = Microsoft.EntityFrameworkCore.EntityState.Modified; _context.Block.Attach(block); _context.Entry(block).State = Microsoft.EntityFrameworkCore.EntityState.Modified; _context.SaveChanges(); } catch { } } else { ModelState.AddModelError(string.Empty, "Tài khoản bị khóa!. Lí do: " + block.Reason); return(Page()); } } } if (ModelState.IsValid) { // This doesn't count login failures towards account lockout // To enable password failures to trigger account lockout, set lockoutOnFailure: true var result = await _signInManager.PasswordSignInAsync(Input.Email, Input.Password, Input.RememberMe, lockoutOnFailure : true); if (result.Succeeded) { string urlavatar = ""; if (user.IsAdmin == 1) { admin = _context.Admin.Where(c => c.Account_ID == user.Id).SingleOrDefault(); urlavatar += admin.Avatar_URL; } else { cus = _context.Customer.Where(c => c.Account_ID == user.Id).SingleOrDefault(); urlavatar += cus.Avatar_URL; } HttpContext.Session.SetString("AvatarImage", urlavatar); _logger.LogInformation("User logged in."); return(LocalRedirect(returnUrl)); } if (result.RequiresTwoFactor) { return(RedirectToPage("./LoginWith2fa", new { ReturnUrl = returnUrl, RememberMe = Input.RememberMe })); } if (result.IsLockedOut) { _logger.LogWarning("User account locked out."); return(RedirectToPage("./Lockout")); } else { ModelState.AddModelError(string.Empty, "Đăng nhập không thành công!."); return(Page()); } } // If we got this far, something failed, redisplay form return(Page()); }
public async Task <IActionResult> OnPostAsync(IFormFile image) { if (!ModelState.IsValid) { return(Page()); } var user = await _userManager.GetUserAsync(User); if (user == null) { return(NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.")); } if (user.IsAdmin == 1) { BDS_ML.Models.ModelDB.Admin admin = _context.Admin.Where(c => c.Account_ID == user.Id).SingleOrDefault(); var email = await _userManager.GetEmailAsync(user); if (admin == null) { return(NotFound($"Unable to load admin with úuerID '{_userManager.GetUserId(User)}'.")); } var oldImage = admin.Avatar_URL; if (image != null) { string fileName = Path.GetFileName(image.FileName); string extensionFileName = Path.GetExtension(fileName); if (fileName.Substring(0, fileName.Length - extensionFileName.Length).Length > 40) { fileName = fileName.Substring(0, fileName.Length - extensionFileName.Length - 40) + "-" + user.Id + "-" + DateTime.Now.ToString().Replace(" ", "").Replace(":", "").Replace("/", "") + extensionFileName; } else { fileName = fileName.Substring(0, fileName.Length - extensionFileName.Length) + "-" + user.Id + "-" + DateTime.Now.ToString().Replace(" ", "").Replace(":", "").Replace("/", "") + extensionFileName; } var path = Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot\images\avatars", fileName); using (var stream = new FileStream(path, FileMode.Create)) { await image.CopyToAsync(stream); } admin.Avatar_URL = fileName; } else { admin.Avatar_URL = "avatar_common.png"; } { try { _context.Admin.Attach(admin); _context.Entry(admin).State = Microsoft.EntityFrameworkCore.EntityState.Modified; _context.SaveChanges(); HttpContext.Session.SetString("AvatarImage", admin.Avatar_URL); if (String.Compare(oldImage, "avatar_common.png", true) != 0) { var path = Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot\images\avatars", oldImage); if (System.IO.File.Exists(path)) { System.IO.File.Delete(path); } } } catch { StatusMessage = "Error Cập nhật thông tin không thành công!"; return(RedirectToPage()); } } } if (user.IsAdmin == 0) { Customer customer = _context.Customer.Where(c => c.Account_ID == user.Id).SingleOrDefault(); var email = await _userManager.GetEmailAsync(user); if (customer == null) { return(NotFound($"Unable to load admin with úuerID '{_userManager.GetUserId(User)}'.")); } var oldImage = customer.Avatar_URL; if (image != null) { string fileName = Path.GetFileName(image.FileName); string extensionFileName = Path.GetExtension(fileName); if (fileName.Length - extensionFileName.Length > 40) { fileName = fileName.Substring(0, 40) + "-" + user.Id + "-" + DateTime.Now.ToString().Replace(" ", "").Replace(":", "").Replace("/", "") + extensionFileName; } else { fileName = fileName.Substring(0, fileName.Length - extensionFileName.Length) + "-" + user.Id + "-" + DateTime.Now.ToString().Replace(" ", "").Replace(":", "").Replace("/", "") + extensionFileName; } var path = Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot\images\avatars", fileName); using (var stream = new FileStream(path, FileMode.Create)) { await image.CopyToAsync(stream); } customer.Avatar_URL = fileName; } else { customer.Avatar_URL = "avatar_common.png"; } { try { _context.Customer.Attach(customer); _context.Entry(customer).State = Microsoft.EntityFrameworkCore.EntityState.Modified; _context.SaveChanges(); HttpContext.Session.SetString("AvatarImage", customer.Avatar_URL); if (String.Compare(oldImage, "avatar_common.png", true) != 0) { var path = Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot\images\avatars", oldImage); if (System.IO.File.Exists(path)) { System.IO.File.Delete(path); } } } catch { StatusMessage = "Error Cập nhật thông tin không thành công!"; return(RedirectToPage()); } } } StatusMessage = "Thông tin của bạn đã được cập nhật"; return(RedirectToPage()); }