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"));
        }
Exemplo n.º 2
0
        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> 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> 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());
            }
        }
Exemplo n.º 5
0
        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());
        }
Exemplo n.º 6
0
        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());
        }